day-16 代码随想录算法训练营(19)二叉树part03

104.二叉树的最大深度

思路一:层序遍历

见day-15

思路二:递归遍历
class Solution {
public:
    int result;
    void judge(TreeNode*root,int deepth)
    {
        result=max(deepth,result);
        if(root->left==nullptr && root->right==nullptr)
            return;
        if(root->left)
            judge(root->left,deepth+1);
        if(root->right)
            judge(root->right,deepth+1);
    }
    int maxDepth(TreeNode* root) {
        if(root==nullptr)
            return 0;
        result=0;
        judge(root,1);
        return result;
    }
};
分析:重点在于全局变量的更新,以及deepth变量作为值传递,每一层的改变并不会影响其他层数据的改变

111.二叉树的最小深度

思路一:跟最大深度差不多,主要就是在叶子节点处更新最小值的变化
class Solution {
public:
    int res;
    void judge(TreeNode*root,int mindeepth)
    {
        if(root->left==nullptr && root->right==nullptr)
            res=min(res,mindeepth);
        if(root->left)
            judge(root->left,mindeepth+1);
        if(root->right)
            judge(root->right,mindeepth+1);
    }
    int minDepth(TreeNode* root) {
        if(root==nullptr)
            return 0;
        res=INT_MAX;
        judge(root,1);
        return res;
    }
};

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

思路一:直接递归遍历(前序),当前节点记录节点数量
class Solution {
public:
    void judge(TreeNode*root,int &nums)
    {
        if(root==nullptr)
            return;
        nums++;
        judge(root->left,nums);
        judge(root->right,nums);
    }
    int countNodes(TreeNode* root) {
        //思路:递归遍历
        if(root==nullptr)
            return 0;
        int nums=0;
        judge(root,nums);
        return nums;
    }
};
思路二:层序遍历,在每一层节点数量nums+=que.size()

110.平衡二叉树

分析:这一题判断的是每个节点的左右子树的高度差是否小于等于1
思路:后序递归
class Solution {
public:
    int judge(TreeNode*root)
    {
        if(root==nullptr)
            return 0;
        int deepl=judge(root->left);
        if(deepl==-1)  return -1;
        int deepr=judge(root->right);
        if(deepr==-1)  return -1;

        int res=0;
        if(abs(deepl-deepr)>1) return -1;
        else{
            res=1+max(deepl,deepr);
        }
        return res;
    }
    bool isBalanced(TreeNode* root) {
        //思路:递归遍历计算每一个叶子节点的深度,判断是否和其他叶子节点的最大深读相差1
        //思路二:递归遍历每一个节点的左右子树深度,判断是否差值小于等于1
        if(root==nullptr)
            return true;
        return judge(root)==-1?false:true;
    }
};
分析:求二叉树的深度和高度需要明确遍历的顺序,高度必然是后序,因为需要先判断左右子树的高度

你可能感兴趣的:(代码随想录算法训练营(19期),算法学习,C++,算法,leetcode,数据结构)