LeetCode Maximum Depth of Binary Tree
来源:互联网 发布:淘宝网铁皮剪刀 编辑:程序博客网 时间:2024/04/29 12:54
题目:
就是来计算一棵二叉树的最大深度。首先我们设想,二叉树的最大深度,就是由最底层的深度所决定,但是具体是左子树还是右子树的深度,这个就得根据具体这棵树的结构决定了,那么我们如何来计算呢?首先我想到的是用递归来计算,就是从左子树和右子树来看,通过递归去遍历。
<span style="font-size:14px;">class TreeNode{ int val; TreeNode left; TreeNode right; TreeNode(int x) { x = val; }}public class Solution{ int length = 0; public int maxDepth(TreeNode root) { if(root == null) return 0; int leftDepth = maxDepth(root.left) + 1; int rightDepth = maxDepth(root.right) + 1; length = leftDepth > rightDepth ? leftDepth : rightDepth; return length; }}</span>这里的那个方法中用了递归,直到遇到叶子节点为止,那么这课二叉树的遍历也就结束了,这样这个二叉树的深度也就求出来了。
这个递归过程有点难想到,它里面是一层套着一层循环,但是最后返回的结果是到第一次开始进入这个递归的那个地方开始。
0 0
- Leetcode - Tree - Maximum Depth of Binary Tree
- [leetcode][tree] Maximum Depth of Binary Tree
- LeetCode Maximum Depth of Binary Tree
- [Leetcode] Maximum Depth of Binary Tree
- leetcode 24: Maximum Depth of Binary Tree
- [LeetCode] Maximum Depth of Binary Tree
- Leetcode 104 Maximum Depth of Binary Tree
- 【leetcode】Maximum Depth of Binary Tree
- [leetcode]Maximum Depth of Binary Tree
- [LeetCode]Maximum Depth of Binary Tree
- [leetcode]Maximum Depth of Binary Tree
- Leetcode: Maximum Depth of Binary Tree
- LeetCode-Maximum Depth of Binary Tree
- [leetcode] Maximum Depth of Binary Tree
- LeetCode - Maximum Depth of Binary Tree
- LeetCode:Maximum Depth of Binary Tree
- LeetCode | Maximum Depth of Binary Tree
- 【leetcode】Maximum Depth of Binary Tree
- 3步带你快速了解特斯拉“巨大充电宝”
- 携不符合安全标准充电宝禁止登机
- 对HDFS进行操作——笔记
- CATransition转场动画
- 滚动视图UIScrollView、UIPageControl
- LeetCode Maximum Depth of Binary Tree
- django 1.8 官方文档翻译: 8-3 点击劫持保护
- ExtJS4组件_form表单配置-属性-方法详解
- [知乎]12306 系统在 2015 年春运高峰期的稳定运行,采用了哪些具体技术?
- 比那名居天子
- 代码面试最常用的10大算法
- HDU 5437 Alisha’s Party(优先队列+模拟)——2015 ACM/ICPC Asia Regional Changchun Online
- java 中 for 与 while 比较。
- hadoop 学习笔记:mapreduce框架详解