111

題目:
https://leetcode.com/problems/minimum-depth-of-binary-tree/description/

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
int minDepth(TreeNode* root) {
if(root == nullptr) return 0; // empty tree
if(root->left == nullptr && root->right == nullptr) return 1; // leaf node
int ldepth = INF, rdepth = INF; // initially set to INF to prevent undefined value
if(root->left != nullptr) ldepth = minDepth(root->left);
if(root->right != nullptr) rdepth = minDepth(root->right);
return min(ldepth, rdepth) + 1; // the smaller one plus myself
}
};