Leetcode Minimum Depth of Binary Tree

OpenSoucre發表於2014-06-26

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.

注意題目到達的時葉子節點

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

 

相關文章