【问题标题】:Trying to find the parent of a node in a binary tree试图在二叉树中找到节点的父节点
【发布时间】:2016-11-06 06:22:17
【问题描述】:

我正在尝试实现一个在二叉树中查找给定节点的父节点的函数,但该函数始终返回根节点。我不知道如何使它工作。我已经尝试了好几天了。

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;
}

【问题讨论】:

    标签: c binary-tree


    【解决方案1】:
            return parent = a;
    

    不是 C(或者至少,它不是您认为 C 在这里所做的)。

    你只想要类似的东西

    return a;
    

    【讨论】:

      【解决方案2】:

      您需要捕获对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;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-08-24
        • 2023-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-28
        • 1970-01-01
        相关资源
        最近更新 更多