【代码随想录第16天】二叉树3

104. 二叉树的最大深度(简单)

题目链接:104. 二叉树的最大深度
代码随想录:104. 二叉树的最大深度

1.迭代法:层序遍历
2.递归法 (后序遍历)

public:
    int maxDepth(TreeNode* root) {
        if(root == nullptr) return 0;
        int left = maxDepth(root -> left);
        int right = maxDepth(root -> right);
        return 1 + max(maxDepth(root -> left), maxDepth(root -> right));
    }
};

111. 二叉树的最小深度(简单)

LeetCode题目:111. 二叉树的最小深度
代码随想录:111. 二叉树的最小深度

1.第一反应思路:迭代法层序遍历

class Solution {
public:
    int minDepth(TreeNode* root) {
        int depth = 0;
        queue<TreeNode *> que;
        if(root) que.push(root);
        while(!que.empty()){
            int size = que.size();
            depth++;
            for(int i = 0; i < size; i++){
                TreeNode * cur = que.front();
                que.pop();
                if(cur->left) que.push(cur->left);
                if(cur->right) que.push(cur->right);
                if(!cur->left && !cur->right)
                    return depth;
            }
        }
        return depth;
    }
};

递归有点难想

自己写的

int minDepth(TreeNode* root) {
     if(!root) return 0;
     //右空左不空,最小深度往左边找
     if(root->left && !root->right)
         return 1 + minDepth(root->left);
     //左空右不空,最小深度往右找
     if(!root->left && root->right)
         return 1 + minDepth(root->right);
     return 1 + min(minDepth(root->left), minDepth(root->right));
}

222. 完全二叉树的节点个数(中)

LeetCode题目:222. 完全二叉树的节点个数
代码随想录:222. 完全二叉树的节点个数

完全二叉树节点数n = 2h -1

class Solution {
public:
    int countNodes(TreeNode* root) {
        if(!root) return 0;
        int leftD = 0, rightD = 0;
        TreeNode * left = root->left;
        TreeNode * right = root->right;
        while(left){
            leftD++;
            left = left->left;
        }
        while(right){
            rightD++;
            right = right->right;
        }
        // 完全二叉树
        if(leftD == rightD) 
            return (2<<leftD) - 1;
        else
            return 1 + countNodes(root->left) +countNodes(root->right);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值