Java 什么';这两个求二叉树最大深度的代码有什么不同?
我正在解决这个leetcode问题: 给定一棵二叉树,求其最大深度 最大深度是从根节点到最远叶节点的最长路径上的节点数 工作代码:Java 什么';这两个求二叉树最大深度的代码有什么不同?,java,algorithm,recursion,tree,Java,Algorithm,Recursion,Tree,我正在解决这个leetcode问题: 给定一棵二叉树,求其最大深度 最大深度是从根节点到最远叶节点的最长路径上的节点数 工作代码: public class Solution { public int maxDepth(TreeNode root) { if(root == null) return 0; int left = maxDepth(root.left); int right = maxDepth(
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;
}
}
非工作代码:
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;
}
}
有人能解释一下为什么一个不起作用吗?递归伤到了我的头。在第一个例子中,你说的很有效,
左
和右
是maxDepth
中的局部变量,因此对maxDepth
的每个调用都有自己的私有副本,其他调用maxDepth
无法更改
在第二个示例中,left
和right
是实例字段,因此该实例上对maxDepth
的所有调用都将共享它们。因此,当maxDepth
调用其自身时,它会覆盖任何包含调用的left
和right
中的值。例如,这里:
left = maxDepth(root.left);
right = maxDepth(root.right);
…第一个调用返回
left
的值,然后被第二个调用覆盖,因为第二个调用也执行left=maxDepth(root.left)代码>。此外,如果您最终进一步递归(您可能会这样做),left
和right
都会被覆盖。在您所说的第一个示例中,left
和right
都是maxDepth
中的局部变量,因此,对maxDepth
的每个调用都有自己的私有副本,其他对maxDepth
的调用无法更改
在第二个示例中,left
和right
是实例字段,因此该实例上对maxDepth
的所有调用都将共享它们。因此,当maxDepth
调用其自身时,它会覆盖任何包含调用的left
和right
中的值。例如,这里:
left = maxDepth(root.left);
right = maxDepth(root.right);
…第一个调用返回left
的值,然后被第二个调用覆盖,因为第二个调用也执行left=maxDepth(root.left)代码>。此外,如果您最终进一步递归(您可能会这样做),左
和右
都会被覆盖。“有人能解释一下为什么它们都不工作吗?”您已经说过第一个可以工作。等等,它说有一个工作代码,但没有工作代码,然后询问它们为什么都不工作。有点困惑“有人能解释为什么他们都不工作吗?”你说第一个能工作。等等,它说有一个工作代码和一个不工作代码,然后问他们为什么都不工作。有点困惑