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) {
return subMinDepth(root,0);
}
int subMinDepth(TreeNode *node,int curDepth){
if(node==NULL){
return curDepth;
}
curDepth++;
int left=subMinDepth(node->left,curDepth);
int right=subMinDepth(node->right,curDepth);
if(node->left==NULL)
return right;
else if(node->right==NULL)
return left;
if(left>right)
return right;
else return left;
}
};