【发布时间】: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