Day16 | 104.二叉树的最大深度, 559.n叉树的最大深度, 111.二叉树的最小深度, 222.完全二叉树的节点个数 (递归)

Day16 | 104.二叉树的最大深度, 559.n叉树的最大深度, 111.二叉树的最小深度, 222.完全二叉树的节点个数 (递归)

二叉树高度和深度的区别:https://blog.csdn.net/demonandyu/article/details/85331904

二叉树的最大深度

LeetCode题目:https://leetcode.cn/problems/maximum-depth-of-binary-tree/

解题思路

  要注意递归的整体架构可以确定为前序遍历,中序遍历,后序遍历三种类型。需要确定递归所需要哪种遍历类型,以此来进行相应的递归操作。

  代码:

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

n叉树的最大深度

LeetCode题目:https://leetcode.cn/problems/maximum-depth-of-n-ary-tree/

解题思路

  类似于二叉树最大深度,多进行几轮比较即可。

  代码:

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

二叉树的最小深度

LeetCode题目链接:https://leetcode.cn/problems/minimum-depth-of-binary-tree/

解题思路

  本题应当注意的是,比较的最小深度指的是root节点到最近的叶子节点的深度,不能直接判定如果左右子树有一个为null便直接返回数值。如果存在null应当忽略该子树的信息。

  具体代码如下:

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

完全二叉树的节点个数

LeetCode题目链接:https://leetcode.cn/problems/count-complete-tree-nodes/

完全二叉树定义:https://blog.csdn.net/JMW1407/article/details/108204019

解题思路

  完全二叉树由于特有的性质,可以看做是很多个小的满二叉树的集合,因此可以通过满二叉树的特性来进行计算,即满二叉树的节点个数为 2 n − 1 2^n-1 2n1,n为满二叉树的高度。因此,可以当判定节点空或者为满二叉树时,计算节点数并返回,如果没有满足,则向下递归。

  具体代码如下:

class Solution {
public:
    int countNodes(TreeNode* root) {
        if(root==NULL){
            return 0;
        }
        int lengthLeft = 0,lengthRight=0;
        TreeNode* left = root->left;
        TreeNode* right = root->right;
        while(left!=NULL){
            left = left->left;
            lengthLeft++;
        }
        while(right!=NULL){
            right = right->right;
            lengthRight++;
        }
        if(lengthRight==lengthLeft){
            return (2<<lengthLeft)-1;
        }
        int numLeft = countNodes(root->left);
        int numRight = countNodes(root->right);
        return numLeft+numRight+1; 
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值