代码随想录算法训练营第十四天 | 104.二叉树的最大深度; 111.二叉树的最小深度;222.完全二叉树的节点个数

104. 二叉树的最大深度

之前用层序遍历迭代法写过;

递归法:

class Solution {
public:
    int getDepth(TreeNode* root){
        if(root==NULL) return 0;
        int leftdeep = getDepth(root->left);
        int rightdeep = getDepth(root->right);
        int depth = max(leftdeep,rightdeep) + 1;
        return depth;
    }
    int maxDepth(TreeNode* root) {
        return getDepth(root);
    }
};

递归法主要有三个步骤,第一步确定输入的参数,第二部确定递归终止条件,第三步确定单次递归内逻辑;用后序遍历代码好写;

111. 二叉树的最小深度

递归法:

class Solution {
public:
    int getDepth(TreeNode* node){
        if(node==NULL) return 0;
        int leftdeep = getDepth(node->left);
        int rightdeep = getDepth(node->right);
        if(node->left==NULL&&node->right){
            return 1 + rightdeep;
        }
        if(node->right==NULL&&node->left){
            return 1 + leftdeep;
        }
        int result = 1 + min(rightdeep,leftdeep);
        return result;
    }
    int minDepth(TreeNode* root) {
        return getDepth(root);
    }
};

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

普通二叉树:

递归:

class Solution {
public:
    int getNode(TreeNode* node){
        if(node==NULL) return 0;
        int leftNum = getNode(node->left);
        int rightNum = getNode(node->right);
        int num = leftNum + rightNum + 1;
        return num;
    }
    int countNodes(TreeNode* root) {
        return getNode(root);
    }
};

迭代:

class Solution {
public:
    int countNodes(TreeNode* root) {
        queue<TreeNode*> que;
        int num = 0;
        if(root!=NULL) que.push(root);
        while(!que.empty()){
            int size = que.size();
            for(int i = 0;i<size;i++){
                TreeNode* cur = que.front();
                que.pop();
                num++;
                if(cur->left!=NULL) que.push(cur->left);
                if(cur->right!=NULL) que.push(cur->right);
            }
        }
        return num;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值