题目描述
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
总结
二叉树就看看吧,反正过了又忘了(滑稽),这种题就就留的看了。
SC思路:当前结点深度等于左右子树中较大的那个深度加一。
Sample Code
class Solution {
public int maxDepth(TreeNode root) {
// 一行代码解决的方法
// return root == null ? 0 : Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
if(root == null) return 0;
int l1=maxDepth(root.left);
int l2=maxDepth(root.right);
return Math.max(l1,l2)+1;
}
}
ERROR Code
树中的null值会影响结果。这不是我的错(愤愤不平~)。
root.left和root.right判断的不是值,而是对象,测试用例[3,9,20,null,null,15,7]中的值只能用root==null判断。
class Solution {
int max = 0, cur = 0;
public int maxDepth(TreeNode root) {
if(root == null) return 0;
if(root.left == null && root.right == null) return 1;
max = fl(root);
return max;
}
private int fl(TreeNode n) {
if(n == null) return max = Math.max(max, cur+1);
if(n.left == null && n.right == null) {
max = Math.max(max, cur+1);
cur--;
return max;
}
cur++;
return Math.max(fl(n.left), fl(n.right));
}
}