LeetCode 111. 二叉树的最小深度
原题链接
简单
作者:
yahoo17
,
2020-07-20 21:56:44
,
所有人可见
,
阅读 528
解法1 递归
/**
* 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) return 0;
if(!root->left&&!root->right) return 1;
if(root->left&&root->right) return 1+min(minDepth(root->left),minDepth(root->right));
if(root->left) return minDepth(root->left)+1;
return minDepth(root->right)+1;
}
};
解法2 BFS
class Solution {
public:
int minDepth(TreeNode* root) {
if(!root) return 0;
return bfs(root);
}
int bfs(TreeNode * u){
queue<pair<TreeNode *,int>> q;
q.push(make_pair(u,1));
while(q.size()){
auto t=q.front();
q.pop();
TreeNode * node=t.first;
if(!node->left&&!node->right)
return t.second;
if(node->right) q.push(make_pair(node->right,t.second+1));
if(node->left) q.push(make_pair(node->left,t.second+1));
}
return -1;
}
};