繁体   English   中英

如何返回 C 中树中特定值的指针?

[英]how to return the pointer of a specific value in a tree in C?

使用这个结构:

typedef struct node {
  int content;
  struct node* right;
  struct node* left;
}Node;

我正在尝试编写一个代码来返回节点的指针 if node ->content== x 我到目前为止已经尝试过了,但我认为它不正确:

 Node* find (Node* p,int x)
{
  Node* L,*R;
    if(p==NULL)
    retutn NULL;
  L=find(p->left,x);
    if(L->content == x)
    return L;
  R=find(p->right,x);
    if(R->content == x)
  return R;
}

你能帮我纠正我的代码吗?

首先,由于retutn ,代码甚至无法编译。


L=(p->left,x);    // Equivalent to: L = x;

应该

L=find(p->left,x);

右侧的想法相同。


L可以是 NULL。

if(L->content == x)

应该

if(L != NULL)

要不就

if(L)

右侧的想法相同。


您永远不会检查当前节点是否匹配。 您需要添加以下内容:

if ( p->content == x )
   return p;

以下是正确的:

Node* L, *R;

但是,很容易不小心做

Node* L, R;

也许您应该避免对此类声明进行分组。 从好的方面来说,这应该在编译时被捕获(除非你避免打开最基本的警告)。


全部一起,

Node* find(Node* p, int x)
{
   if ( !p )
      return NULL;

   if ( p->content == x )
      return p;

   Node* L = find( p->left, x );
   if ( L )
      return L;

   Node* R = find( p->right, x );
   if ( R )
      return R;

   return NULL;
}

从这些语句开始的 function 部分

L=find(p->left,x);
  if(L->content == x)
  return L;

是不正确的。 对于初学者来说,不清楚为什么不检查指针 p 指向的节点。 而function的调用可以返回一个null指针。 所以这个 if 语句可以调用未定义的行为。

function 定义取决于它是否是二叉搜索树。 那就是树的节点是否有序。

如果它不是二叉搜索树,则可以通过以下方式定义 function

Node * find( const Node *root, int x )
{
    if ( root == NULL )
    {
        return NULL;
    }
    else if ( root->content == x )
    {
        return ( Node * )root;
    }
    else
    {
        Node *p = find( root->left, x );
        p == NULL ? return find( root->right, x ) : p;
    }
}

如果树是二叉搜索树,那么 function 可以如下所示

Node * find( const Node *root, int x )
{
    if ( root == NULL )
    {
        return NULL;
    }
    else if ( x < root->content )
    {
        return find( root->left, x );
    }
    else if ( root->content < x )
    {
        return find( root->right, x );
    }
    else
    {
        return ( Node * )root;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM