简体   繁体   English

二叉树,返回节点的父级

[英]Binary tree,return the parent of the node

I try to write a function which return the parent of the value node.The createAB function works,but i don't know to iterate the binary tree elements.How to make recursively call?.Please help me. 我尝试编写一个返回值节点的父级的函数。createAB函数有效,但是我不知道要迭代二叉树元素。如何进行递归调用?请帮助我。

 ifstream f("store.txt");//store.txt:10 7 8 0 0 0 13 9 0 11 0 0 12 0 0
    struct elem {
        int inf;
        elem* st;
        elem* dr;
    };
    //this function create the binary tree
    void createAB(elem*& p) {
        int n;
        f >> n;
        if (n!=0) {
            p = new elem;
            p->inf = n;
            createAB(p->st);
            createAB(p->dr);
        }
        else 
            p = NULL;
    }
    `

        elem* parent(elem* rad, int n) {//my function,doesn't work
        if (rad == NULL)
            return NULL;
        else
            if (rad->st->inf == n || rad->dr->inf == n) 
                return rad;//return the element
            else {
                return parent(rad->st, n);//here is a problem
                return parent(rad->dr, n);
            }
    }
      10
   7       13
 8       9    12
           11
node 12 => parent 13
node 8 => parent 7

在使用rad->st->infrad->dr->inf之前,应检查rad->strad->dr是否为null。

As pointed out by sebi519, you need to check that rad->st and rad->dr are not NULL . 正如sebi519指出的那样,您需要检查rad- rad->strad->dr不为NULL

But as you correctly commented the main problem here is in the return statements. 但是正如您正确评论的那样,这里的主要问题是在return语句中。 The problem is that the second line is never executed as the first line already returns from the function. 问题是第二行永远不会执行,因为第一行已经从函数返回。

return parent(rad->st, n);//This returns and the next line is not executed
return parent(rad->dr, n);

You need to save the result of the first call and check if it was successful and if not then do the second call: 您需要保存第一个调用的结果,并检查是否成功,否则,请执行第二个调用:

elem* result = parent(rad->st,n);
if (result != NULL)
  return result;
else
  return parent(rad->dr,n);

Full corrected function: 完全纠正的功能:

elem* parent(elem* rad, int n) {
  if (rad == NULL)
    return NULL;
  else
    if ( (rad->st!=NULL && rad->st->inf == n) || (rad->dr!=NULL) && (rad->dr->inf == n)){
      return rad;//return the element
    }
    else {
      elem* result= parent(rad->st, n);
      if (result!=NULL){
        return result;
      }
      else{
        return parent(rad->dr, n);
      }
    }
}

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

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