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还是很重要的。
代码如下:
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); } }
相关文章推荐
- __get(),__set(),__isset(),__unset()
- linux下文件系统类型的学习
- Mongo管理用户相关操作总结
- iOS动画 核心动画
- cell?.viewWithTag 为 nil
- Spring 从零开始-04
- 数据库操作
- 腾讯手机QQ共享WiFi密码引投诉
- MFC设置对话框背景色及控件颜色
- 安装Eclipse插件长时间卡在 calculating requirements and dependencies
- [华为机试练习题]52.Fibonacci数列的计算和转换
- 虚拟机攻防技术(转)
- Android检测是否安装了某个应用,同时进行App间的跳转
- 计算机网络基础知识整理(二)
- Flash镜头移动效果制作
- 整型反序
- 不使用加减乘除,求一个数的7倍
- Fragment同时适配手机和平板两种屏幕
- KMP字符串匹配算法实现
- 基本正则表达式grep命令使用