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.

分析:

注意logic很有意思,当leaf结点的时候,应该返回1,返回0是不对的,这个带入只有root的情况就可以验证

解法:

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 lHeight = Integer.MAX_VALUE;
        int rHeight = Integer.MAX_VALUE;
        if (root.left != null) {
            lHeight = minDepth(root.left);
        }
        if (root.right != null) {
            rHeight = minDepth(root.right);
        }
        return Math.min(lHeight, rHeight) + 1;
    }
}

results matching ""

    No results matching ""