题目:
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.
解答:/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode *root) {
if(root == NULL) {
return 0;
}
if(root->left == NULL) {
return 1 + minDepth(root->right);
}
if(root->right == NULL) {
return 1 + minDepth(root->left);
}
return 1 + min(minDepth(root->left), minDepth(root->right));
}
};
思路:
和“Maximum Depth of Binary Tree”有区别,求min时如果某一个分支为NULL,这个分支是忽略不计的,不能算成1+min(有分支的min,0)