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 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) {
return minDepth(root,false);
}
int minDepth(TreeNode* root,bool hasBrother){
if(!root) return hasBrother?INT_MAX:0;
return(1+min(minDepth(root->left,root->right!=NULL),minDepth(root->right,root->left!=NULL)));
}
};