[LeetCode][二叉树]Maximum Depth of Binary Tree
2016-03-21 12:19
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.
思路:
前提:二叉树,只包含左右两个子树,最大的深度就是左右两子树的最大深度+1,就是左子树的左右两子树的最大深度+2或右子树的左右两子树的最大深度+2
过程:递归,每次递归只返回当前输入根的最大深度,所以深度初始设置为0,通过递归获取左子树和右子树的深度,选择数值较大的深度+1就是当前输入根的最大深度,初始输入为root根节点即可,递归的终止条件是输入根为null
代码实现:
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.
思路:
前提:二叉树,只包含左右两个子树,最大的深度就是左右两子树的最大深度+1,就是左子树的左右两子树的最大深度+2或右子树的左右两子树的最大深度+2
过程:递归,每次递归只返回当前输入根的最大深度,所以深度初始设置为0,通过递归获取左子树和右子树的深度,选择数值较大的深度+1就是当前输入根的最大深度,初始输入为root根节点即可,递归的终止条件是输入根为null
代码实现:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int maxDepth(TreeNode root) { int depth = 0; if(root != null){ int leftDepth = maxDepth(root.left); int rightDepth = maxDepth(root.right); depth++; if(leftDepth < rightDepth){ depth = depth + rightDepth; }else{ depth = depth + leftDepth; } } return depth; } }
相关文章推荐
- 删除文件
- LeetCode Minimum Height Trees
- 安卓属性动画(Property Animation)(上)
- appium在真机上运行IOS实例要注意的几点:包括python和java运行log 和部分关键代码
- 阻塞式线程安全列表
- 如何在关闭SSH Session的情况下,程序还能继续运行
- java static关键字用法详解
- JavaScript系列:正则表达式
- 关于对张伟祥同学的代码复审!
- PHP进阶篇:取得日期的Unix时间戳
- CENTOS 内存释放
- OpenCV HOG Detector: Result Clustering
- 阅读程序 回答问题——FindTheNumber
- ajax与HTML5 history pushState/replaceState实例
- PullToRefreshViewPager和ViewPager制作卡片效果
- myeclipse 2015 stable 2.0连接mysql URL错误
- iOS AssetsLibrary和Photos的使用总结: 原图获取(2)
- LeetCode "Counting Bits"
- 栈在java中的实现
- mysql锁-乐观锁