您的位置:首页 > 其它

Maximum Depth of Binary Tree

2015-07-04 15:56 330 查看
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Show Tags

Have you met this question in a real interview?
上一篇用DFS求了最小深度,这里用同样的方法求最大,所以只需在上一篇的基础上求出集合里面的最大值即可。Collections工具类非常好用,对list排序,求list中最大,最小值都ok。熟悉API还是很重要的。
代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private ArrayList<Integer> list = new ArrayList<Integer>();
public int maxDepth(TreeNode root) {
if(root==null) return 0;
dfs(root,0);
//Collections工具类非常好用,对list排序,求list中最大,最小值都ok
return  Collections.max(list);
}

public void dfs(TreeNode root,int count){
if(root==null){
return;
}else{
count++;
if(root.left==null&&root.right==null){
list.add(count);
return;
}
}

dfs(root.left,count);
dfs(root.right,count);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: