当我尝试提交在ldepth
块之前声明rdepth
和if-else
变量的代码时,该代码为测试用例提供了错误的解决方案。
我理解并能够提交有效的递归解决方案,其中ldepth
和rdepth
变量在else语句中本地声明。
为什么必须在if-else
块中声明这些变量?
这是我不正确的解决方案:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
int depth;
int rdepth;
int ldepth;
if (root == null) {
return 0;
}
else {
ldepth = maxDepth(root.left);
rdepth = maxDepth(root.right);
if (ldepth > rdepth) {
depth = ldepth + 1;
return depth;
}
if (rdepth > ldepth) {
depth = rdepth + 1;
return depth;
}
else {
depth = rdepth + 1;
return depth;
}
}
}
}