给定一个二叉树,找出其最小深度。
二叉树的最小深度为根节点到最近叶子节点的距离。
样例
给出一棵如下的二叉树:
1
/ \
2 3
/ \
4 5
这个二叉树的最小深度为 2
【主要在递归时要注意,当有的节点有一个子树为空时,不是叶子节点要继续寻找】
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: An integer.
*/
public int minDepth(TreeNode root) {
// write your code here
if(root==null)
return 0;
if(root.left==null && root.right==null)
return 1;
int dep1=minDepth(root.left)+1;
int dep2=minDepth(root.right)+1;
if(dep1==1)//左空右不空
dep1=Integer.MAX_VALUE;
if(dep2==1)
dep2=Integer.MAX_VALUE;
if(dep1>dep2)
return dep2;
return dep1;
}
}
//网上学习的方法
- public class Solution {
- public int minDepth(TreeNode root) {
- if(root == null) return 0;
- if(root.left == null)return minDepth(root.right) + 1;
- if(root.right == null) return minDepth(root.left) + 1;
- return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
- }
- }
这是一篇关于计算二叉树最小深度的文章。主要内容包括理解二叉树的最小深度定义,即从根节点到最近叶子节点的距离。通过提供一个样例二叉树,文章解释了如何递归地寻找最小深度。在递归过程中,特别强调了当节点的一个子树为空时,仍需要继续搜索另一子树的情况。示例中给出了一个解决方案,包含一个名为`Solution`的类,其中`minDepth`方法利用递归计算最小深度。
1322

被折叠的 条评论
为什么被折叠?



