Wednesday, July 22, 2015

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.

一开始想用maximum depth of binary tree的算法来解,只把max 换成了min,以为会得出答案, 但是最后发现minimum这道题 跟maximum还是不同的,因为depth必须要达到树的leaf node,如果直接用min来返回的话,可能结果不是leaf node的depth, 所以必须在基础上做些改变,如果left 或者right有一个是0的话,说明有一边是NULL, 必须返回非NULL那边的depth + 1, 否则,就可以直接取最小的那个值 + 1返回。 这个思路是改进后的代码,在updated那里,这个代码更加简短。

class Solution {
private:
    void helper(TreeNode* root, int &min1, int path) {
        //base case
        if (root == NULL) {
            path = 0;
            return;
        }
        if (!root->left && !root->right) {
            path += 1;
            min1 = min(min1, path);
            return;
        }
        helper(root->left, min1, path+1);
        helper(root->right, min1, path+1);
    }
public:
    int minDepth(TreeNode* root) {
        if (root == NULL) return 0;
        int min1 = INT_MAX;
        helper(root, min1, 0);
        return min1;
    }
};


updated:

class Solution {
public:
    int minDepth(TreeNode* root) {
        if (root == NULL) return 0;
        int left = minDepth(root->left);
        int right = minDepth(root->right);
        if (left * right !=0) return min(left, right)+1;
        if (left == 0) return right+1;
        if (right == 0) return left+1;
    }
};

No comments:

Post a Comment