给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
返回它的最小深度 2.
/**递归
* 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 getMin(TreeNode* root){
if(root == nullptr) return 0;
int leftDepth = getMin(root->left);
int rightDepth = getMin(root->right);
if(root->left == nullptr && root->right != nullptr){
return 1 + rightDepth;
}
if(root->left !=nullptr && root->right == nullptr){
return 1 + leftDepth;
}
return 1 + min(leftDepth, rightDepth);
}
int minDepth(TreeNode* root) {
if(root == nullptr) return 0;
return getMin(root);
}
};
/**迭代法:层次遍历
* 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 == nullptr) return 0;
queue<TreeNode*> que;
que.push(root);
int depth = 0;
int flag = 0;
while(!que.empty()){
int size = que.size();
depth++;
for(int i = 0; i<size; i++){
TreeNode* node = que.front();
que.pop();
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
if(!node->left && !node->right){
flag = 1;
break;
}
}
if(flag == 1) break;
}
return depth;
}
};