【问题标题】:What's the difference between these two code for find the max depth of a binary tree?这两个用于查找二叉树最大深度的代码有什么区别?
【发布时间】:2015-10-19 03:20:46
【问题描述】:

我正在解决这个 leetcode 问题:

https://leetcode.com/problems/maximum-depth-of-binary-tree/

给定一棵二叉树,求其最大深度。

最大深度是从根节点到最远叶节点的最长路径上的节点数。

工作代码:

public class Solution {
    public int maxDepth(TreeNode root) {

        if(root == null)
            return 0;

        int left = maxDepth(root.left);
        int right = maxDepth(root.right);

        if(left > right)
            return left + 1;
        else
            return right + 1;
    }
}

非工作代码:

public class Solution {
    int left = 0;
    int right = 0;
    public int maxDepth(TreeNode root) {

        if(root == null)
            return 0;

        left = maxDepth(root.left);
        right = maxDepth(root.right);

        if(left > right)
            return left + 1;
        else
            return right + 1;
    }
}

有人可以解释为什么一个不起作用吗?递归让我头疼。

【问题讨论】:

  • “有人能解释一下为什么它们都不起作用吗?”你已经说过第一个起作用起作用了。
  • 等等,它说有一个工作代码和一个不工作代码,然后问为什么它们都不起作用。有点迷茫

标签: java algorithm recursion tree


【解决方案1】:

在您所说的第一个示例中,leftrightmaxDepth 中的局部变量,因此每个调用 到@ 987654324@ 有自己的私有副本,其他对maxDepth 的调用无法更改。

在第二个示例中,leftright 是实例字段,因此在该实例上对 maxDepth 的所有调用都将共享它们。因此,当maxDepth 调用自己时,它会覆盖来自任何包含调用的leftright 中的值。例如,这里:

left = maxDepth(root.left);
right = maxDepth(root.right);

...第一次调用返回left 的值,然后第二次调用覆盖,因为第二次调用也执行left = maxDepth(root.left);。此外,如果您最终进一步递归(您可能会这样做),left right 都会被覆盖。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-14
    • 1970-01-01
    • 2016-01-24
    • 2015-02-12
    • 2012-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多