LeetCode 111. 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.

This is the problem that can be solved recursion; all we need to do is write the right equation:
minDepth(root) = Math.min(minDepth(root.left), minDepth(root.right)) + 1;
看起来跟求Max depth没有什么区别,但是就是不对。
难道不是:
root的最小高度 = 最小高度(左子树最小高度,右子树最小高度)+ 1;?

实际上仔细想一想 不是这样的 当左子树或者右子树为null的时候
root的最小高度 = 最大高度(左子树最小高度,右子树最小高度)+ 1;

class Solution {
    public int minDepth(TreeNode root) {
        if(root == null) return 0;
        if(root.left == null || root.right == null){
            return Math.max(minDepth(root.left), minDepth(root.right)) + 1;
        }
        return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
    }
}
posted @ 2020-11-13 03:16  EvanMeetTheWorld  阅读(22)  评论(0)    收藏  举报