簡體   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