//minmum-depth-of-binary-tree
//递归深度优先
class Solution {
public:
int run(TreeNode *root) {
if(root == NULL)return 0;
int l = run(root->left);
int r = run(root->right);
if(l == 0 || r == 0)//有斜树的情况,即根节点的只有左子树有节点
return 1 + r + l;
return min(l,r) + 1;
}
};
//非递归,层次遍历
class Solution {
public:
int run(TreeNode *root) {
if(root == NULL)return 0;
if(root->left == NULL && root->right == NULL)
return 1;
queue<TreeNode*> qu;
TreeNode * t = NULL;
int count = 1;
qu.push(root);
qu.push(NULL);// 每一层入队后以NULL节点标记下
while(!qu.empty()){
t = qu.front();
qu.pop();
if(t == NULL){
qu.push(NULL);
count++;
continue;
}
if(t->left == NULL && t->right == NULL)
return count;
if(t->left != NULL)qu.push(t->left);
if(t->right!= NULL)qu.push(t->right);
}
return count;
}
};
Leetcode----minmum-depth-of-binary-tree
最新推荐文章于 2020-03-15 22:36:12 发布