Monday, September 11, 2017

111. Minimum Depth of Binary Tree

https://leetcode.com/problems/minimum-depth-of-binary-tree/description/
Recursion, (9 ms)
    int minDepth(TreeNode* root) {
        if(!root) return 0;
        if(!root->left && !root->right) return 1;
        int l = minDepth(root->left);
        int r = minDepth(root->right);
        if(l == 0) return r+1;
        else if(r == 0) return l+1;
        else return min(l,r) + 1;
    }
or, (6 ms)
    void inOrder(TreeNode* node, int d, int& m) {
        if(!node) return;
        if(!node->left && !node->right) {
            m = min(m, d+1);
        }
        inOrder(node->left, d+1, m);
        inOrder(node->right, d+1, m);
    }
    int minDepth(TreeNode* root) {
        if(!root) return 0;
        int m = INT_MAX;
        inOrder(root, 0, m);
        return m;
    }

No comments:

Post a Comment