代码随想录第十六天|Leetcode104.二叉树的最大深度、Leetcode559.n叉树的最大深度、Leetcode111.二叉树的最小深度、Leetcode222.完全二叉树的节点个数

代码随想录第十六天|Leetcode104.二叉树的最大深度、Leetcode559.n叉树的最大深度、Leetcode111.二叉树的最小深度、Leetcode222.完全二叉树的节点个数

Leetcode104.二叉树的最大深度

递归写起来还是简单啊

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

Leetcode559.n叉树的最大深度

递归法确实写起来简单些,层序遍历就是逻辑上更简单些

class Solution {
public:
    int maxDepth(Node* root) {
        if(root==NULL) return 0;
        int result=0;
        for(int i=0;i<root->children.size();i++){
            result=max(result,maxDepth(root->children[i]));
        }
        return result+1;
    }
};

Leetcode111.二叉树的最小深度

还行,这次能自己写出来了,这个最大的坑在于左右子树都为NULL,才算到叶子节点了。

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

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

层序遍历得心应手啊,好爽

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

遍历也不能忘,整一遍,出乎意料的轻松???

class Solution {
public:
    int countNodes(TreeNode* root) {
        if(root==NULL) return 0;
        return countNodes(root->left)+countNodes(root->right)+1;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值