Minimum Depth of Binary Tree

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.

求二叉树的最小深。其实有个题目是求最大深度,题目类似,但是有一点点的改变。

因为是最小深度,所以必须增加一个叶子判断(因为如果一个节点如果只有左子树或者右子树,我们不能取它的左右子树中小的作为深度,因为那样会是0,我们只有在叶子结点才能判断深度,而在求最大深的时候因为一定会取最大的那个所以不会有这个问题。)这道题有递归和非递归两种办法。

递归解法是比较常规的思路:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int run(TreeNode root) {
        if(root == null){
            return 0;
        }
        if(root.left == null && root.right == null){
            return 1;
        }
        if(root.left == null){
            return run(root.right)+1;
        }
        if(root.right == null){
            return run(root.left)+1;
        }
        return Math.min(run(root.left),run(root.right))+1;
    }
}

非递归的方法暂时不想写。

原文地址:https://www.cnblogs.com/LoganChen/p/8085801.html