题目:

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.

//给定一个二叉树,求其最小深度。最小深度是从根节点到最近的叶结点的最短路径上的结点数。

 

解题思路:

首先,给定的二叉树根节点如果为空,deep=0;

若不为空,则等于其左右结点为根节点的子树的最小深度的最小值加一(即为min(left.deep,right.deep)+1);

 

代码:

public class Solution {
    public int run(TreeNode root) {
        int deep;
        if(root==null){
            deep=0;
        }else{
            if(root.left==null&&root.right==null){
            deep=1;
            }
            if(root.left==null&&root.right!=null){
                deep=run(root.right)+1;
            }else if(root.right==null&&root.left!=null){
                deep=run(root.left)+1;
            }else{
                deep=Math.min(run(root.left)+1,run(root.right)+1);
            }
        }
        return deep;
    }
}

收藏 打印