2016-11-05 175 views
0

我試圖實現一個函數,該函數查找二叉樹中給定節點的父節點,但函數始終返回根節點。我不知道如何使它工作。我一直在努力幾天。試圖找到二進制樹中的節點的父節點

Tree* NodeParent(Tree* a, char c) 
{ 
    Tree *parent = a; 

    if (!EmptyTree(a)) 
    { 
     if ((!EmptyTree(a->Left) && info(a->Left) == c) 
      || (!EmptyTree(a->Right) && info(a->Right) == c)) 
      return parent = a; 

     else 
     { 
      NodeParent(a->Left, c); 
      NodeParent(a->Right, c); 
     } 
    } 

    return parent; 
} 

此外,樹結構

struct tree 
{ 
    char c; 
    Tree* Left; 
    Tree* Right; 
} 

回答

0
 return parent = a; 

不是C(或至少,它不是你認爲C在這裏所做的)。

你只是想要像

return a; 
0

您需要將遞歸調用的返回值採集到NodeParent(a->Left, c)NodeParent(a->Right, c) ...你可以嘗試這樣的事:

Tree* NodeParent(Tree* a, char c) { 
    Tree *parent; 

    // a is empty tree -> return NULL 
    if (EmptyTree(a)) { 
     return NULL; 

    // in this case, a is the parent 
    } else if ((!EmptyTree(a->Left) && info(a->Left) == c) 
     || (!EmptyTree(a->Right) && info(a->Right) == c)) { 
     return a; 

    // search to the left 
    } else if ((parent = NodeParent(a->Left, c)) != NULL) { 
     return parent; 

    // search to the right 
    } else if ((parent = NodeParent(a->Right, c)) != NULL) { 
     return parent; 

    // c not found in sub-trees 
    } else { 
     return NULL; 
    } 
}