二叉树的最大深度与最小深度
2014-10-03 13:39
309 查看
求二叉树的最小深度与最大深度,都是用递归的方法实现。
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
实现代码:
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.
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
实现代码:
public class Solution { public int minDepth(TreeNode root) { if(root == null) return 0; int left=minDepth(root.left); int right=minDepth(root.right); if(left==0) //如果左子树为空,则返回右子树深度 return right+1; if(right==0) //如果右子树为空,则返回左子树深度 return left+1; return left<right ? left+1:right+1; } }
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.
public class Solution { public int maxDepth(TreeNode root) { if (root == null) return 0; return (Math.max(maxDepth(root.left)+1, maxDepth(root.right)+1)); } }
相关文章推荐
- 二叉树的最小高度,最大高度(深度)和宽度
- 二叉树最大 最小深度
- 二叉树的最大深度与最小深度
- 每天一道LeetCode-----计算二叉树的最大深度及最小深度,判断二叉树是否是高度平衡二叉树
- 二叉树的最大深度 & 二叉树的最小深度
- LeetCode—二叉树的最大最小深度
- 求二叉树的最小深度和最大深度
- 二叉树最大深度和最小深度
- leetcode之二叉树类之二叉树深度系列-----104/111/110/108/109 二叉树最大/最小深度/AVL树的判断和由有序序列生成(牵扯分治相关,OJ105/106)
- 二叉树最大深度和最小深度
- 二叉树的最大深度 & 二叉树的最小深度
- 求二叉树的最大深度和最小深度以及之间的差
- 面试题16:递归计算二叉树的最大、最小深度
- 二叉树的最大深度与最小深度
- [Java代码] [Leetcode] Maximum and Minimum Depth of Binary Tree 二叉树的最小最大深度
- 二叉树的最大深度和最小深度
- [lintcode]二叉树最大深度和最小深度
- Leetcode 95. Unique Binary Search Trees II及二叉树最大最小深度镜像树总结
- python_lintcode_97二叉树的最大深度 _155二叉树的最小深度
- Maximum and Minimum Depth of Binary Tree 二叉树的最小最大深度 [java]