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.
解题思路:
这里的深度表示叶子节点到根节点的距离。比如[1, 2]的最小深度为2,而不是1。其代码如下:
/**
* Definition for a binary tree node.
* 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;
}else if(root->left==NULL&&root->right==NULL){
return 1; //表示root是叶子节点
}else if(root->left!=NULL&&root->right==NULL){
return 1 + minDepth(root->left);
}else if(root->left==NULL&&root->right!=NULL){
return 1 + minDepth(root->right);
}else{
return 1 + min(minDepth(root->left), minDepth(root->right));
}
}
};