参考了leetcode题解那本书的:
需要注意:和max depth稍不同,这里注意叶子节点的概念,不要弄错了。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
int isROOT=1;
public:
int minDepth(TreeNode *root) {
return minDepth(root,false);
}
private:
int minDepth(TreeNode *root,bool hasBrother)
{
if(!root)
return hasBrother?INT_MAX:0;
else
return 1+min(minDepth(root->left,root->right!=NULL),minDepth(root->right,root->left!=NULL));
}
};