111. Minimum Depth of Binary Tre
2018-08-26 本文已影响0人
刘小小gogo
image.png
解法一:递归
/**
* 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;
int left = minDepth(root->left);
int right = minDepth(root->right);
if(root->left == NULL) return 1 + right;
if(root->right == NULL) return 1 + left;
return 1 + min(left, right);
}
};
解法二:bfs
注意的是:如何一层记一个数,用for循环来遍历q;
/**
* 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;
queue<TreeNode*> q;
q.push(root);
int depth = 0;
while(!q.empty()){
int k = q.size();
depth++;
for(int i = 0; i < k; i++){
TreeNode* cur = q.front();
q.pop();
if(cur->left == NULL && cur->right == NULL) return depth;
if(cur->left) q.push(cur->left);
if(cur->right) q.push(cur->right);
}
}
return 0;
}
};