这题我还考过别人,试图用一句code完成,然后结合minDepth放在一起考别人。。下一题写minDepth
之前的代码,好大一段,我确实是个认真boy。。。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.List;
import java.util.ArrayList;
public class Solution {
public int maxDepth(TreeNode root) {
// 仍然可以用两种方法实现;1,遍历,while()内部,当list isEmpty()的时候return
// 2, 递归还是那么好写,只要改一下函数名和 Math.max就好了。。。
// solution 1
/* if(root==null) return 0;
List<TreeNode> list = new ArrayList<TreeNode>();
list.add(root);
int depth=0; // 判断初值!!
while(true){
List<TreeNode> current = new ArrayList<TreeNode>();
for(TreeNode node: list){
if(node.left!=null) current.add(node.left);
if(node.right!=null) current.add(node.right);
}
depth++;
list = current;
if(list.isEmpty()) return depth; // 当上一层是最底层的时候,这一层是空的,所以这里把 判断最底层的问题 转化为isEmpty()来表示
} // !!!注意了,当有while(true) 的时候,循环体里面包含了return,那么可以不用在while之外包含return,compiler会识别出 unreachable statement. // 耗时3ms,才5%*/
/* // solution 2
if(root==null) return 0;
if(root.left==null && root.right==null) return 1;
if(root.left==null) return 1+ maxDepth(root.right);
if(root.right==null) return 1+ maxDepth(root.left);
if(root.left!=null && root.right!=null) return 1+ Math.max(maxDepth(root.left), maxDepth(root.right));
return -1;*/
// solution 3, a more concise version of solution2, but the algo is the same;
if(root==null) return 0;
else return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}
public class Solution {
public int maxDepth(TreeNode root) {
if(root==null) return 0;
return 1+Math.max(maxDepth(root.left), maxDepth(root.right));
}
}