111:二叉树的最小深度
题目
给定一个二叉树,找出其最小深度。最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
- 说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最小深度 2.
思路一——递归
本题有一个关键点是题目是指根节点到叶子结点的最小深度,当一个结点仅有一个左子树或右子树时,最小深度应该是左子树或右子树深度+1。针对一个结点,存在以下几种情况:
- 空结点,返回0;
- 左子树/右子树都无,返回1;
- 左子树存在,右子树不存在,则minDepth(root.left) + 1;
- 左子树不存在,右子树存在,则minDepth(root.right)+1;
- 左右子树都存在,则比较左右子树的最小深度,并取最小值,再+1.
package Algorithms.BinaryTree;
public class Mini_depth_of_binarytree {
public static class TreeNode{
//定义二叉树
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;}
}
//递归函数
public static int minDepth(TreeNode root){
if(root == null) return 0;
if(root.left == null && root.right != null) return minDepth(root.right)+1;
else if(root.left != null && root.right == null) return minDepth