这两个用于查找二叉树最大深度的代码有什么区别?
What's the difference between these two code for find the max depth of a binary tree?
我正在解决这个 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;
}
}
有人能解释一下为什么不起作用吗?递归伤脑筋。
在您所说的第一个示例中,left
和 right
是 maxDepth
中的 局部变量 ,依此类推对 maxDepth
的每个调用 都有自己的私人副本,其他对 maxDepth
的调用无法更改。
在第二个示例中,left
和 right
是实例字段,因此在该实例上对 maxDepth
的所有调用将 共享 他们。因此,当 maxDepth
调用自身时,它会覆盖来自任何包含调用的 left
和 right
中的值。例如,这里:
left = maxDepth(root.left);
right = maxDepth(root.right);
...第一次调用 returns left
的值,然后第二次调用 覆盖 ,因为第二次调用也left = maxDepth(root.left);
。此外,如果您最终进一步递归(您可能会这样做),left
和 right
都会被覆盖。
我正在解决这个 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;
}
}
有人能解释一下为什么不起作用吗?递归伤脑筋。
在您所说的第一个示例中,left
和 right
是 maxDepth
中的 局部变量 ,依此类推对 maxDepth
的每个调用 都有自己的私人副本,其他对 maxDepth
的调用无法更改。
在第二个示例中,left
和 right
是实例字段,因此在该实例上对 maxDepth
的所有调用将 共享 他们。因此,当 maxDepth
调用自身时,它会覆盖来自任何包含调用的 left
和 right
中的值。例如,这里:
left = maxDepth(root.left);
right = maxDepth(root.right);
...第一次调用 returns left
的值,然后第二次调用 覆盖 ,因为第二次调用也left = maxDepth(root.left);
。此外,如果您最终进一步递归(您可能会这样做),left
和 right
都会被覆盖。