0
我正在此本文給出了問題:這兩個代碼找到二叉樹的最大深度有什麼區別?
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;
}
}
有人能解釋爲什麼一個不工作?遞歸會傷害我的頭。
*「有人可以解釋他們爲什麼都不起作用嗎?」*你說第一個*做*工作。 –
等一下,它說了一個工作代碼,而不是工作代碼,然後問爲什麼他們都不工作。有點困惑 – bmarkham
頭仍然傷害 –