【问题标题】:Find the total depth of every node in a binary search tree recursively?递归查找二叉搜索树中每个节点的总深度?
【发布时间】:2012-10-10 16:52:34
【问题描述】:

我在这个问题上已经有一段时间了,我不太明白其中的逻辑。假设我有一棵二叉树,如下所示:

        8                    1 * 0 =  0
      /   \
     4    12                 2 * 1 =  2
    / \   / \
   2   6 10 14               4 * 2 =  8
                                    ----
                                     10

我想找到每个节点的深度并将这些数字加在一起得到总数。我现在得到的代码看起来像这样:

private int totalDepth(Node node, int depth) 
{
    if(node == null) 
    {
        return 0;
    }

    return totalDepth(node.left, depth + 1) + totalDepth(node.right, depth + 1);
}

我认为这会在遍历右侧之前递归地在树的左侧(8 -> 4 -> 2)的每个更深的级别中添加一个,但它并不完全有效。

我已经以多种方式调整了此方法,但似乎无法确定我缺少什么。任何帮助将不胜感激。

【问题讨论】:

    标签: java recursion binary-search-tree


    【解决方案1】:
    public virtual int GetLevelById(int id)
            {
                int i = GetParentById(id);
                if (i == 0)
                    return 1;
                else
                    return (1 + GetLevelById(i));
            }
    

    【讨论】:

      【解决方案2】:

      你快到了:你已经把左子树和右子树的结果加起来了,但是你忘了把节点本身的结果加起来:

      return depth                              // myself
           + totalDepth(node.left, depth + 1)   // my left subtree
           + totalDepth(node.right, depth + 1); // my right subtree
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-04-08
        • 1970-01-01
        • 1970-01-01
        • 2012-01-26
        • 1970-01-01
        • 1970-01-01
        • 2010-11-03
        • 1970-01-01
        相关资源
        最近更新 更多