栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

力扣刷题(day0034)平衡二叉树

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

力扣刷题(day0034)平衡二叉树

给定一个二叉树,判断它是否是高度平衡的二叉树。

本题中,一棵高度平衡二叉树定义为:

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。

示例 1:

 输入:root = [3,9,20,null,null,15,7]
 输出:true

示例 2:

 输入:root = [1,2,2,3,3,null,null,4,4]
 输出:false

示例 3:

 输入:root = []
 输出:true

提示:

树中的节点数在范围 [0, 5000] 内

-104 <= Node.val <= 104

前言:

平衡二叉树求的是树的高度,遍历方式与深度不同,深度是从上向下去查找,所以需要前序遍历(中->左->右),而高度只能从下向上去查找,所以需要后序遍历(左->右->中)

前几天做的104.二叉树的最大深度遍历是用的后序遍历,是因为,逻辑是求的根节点的高度,而根节点就是这棵树的最大深度,而真正意义上的求二叉树的最大深度,代码如下:

class Solution {
public:
    int result;
    void getDepth(TreeNode* node,int depth){
        result=depth>result?depth:result;//中
        if(node->left==nullptr&&node->right==nullptr)return;
        if(node->left){
            depth++;
            getDepth(node->left,depth);//左
            depth--;//回溯
        }
        if(node->right){
            depth++;
            getDepth(node->right,depth);//右
            depth--;//回溯
        }
        return ;
    }
    int maxDepth(TreeNode* root) {
        result=0;
        if(root==0)return result;
        getDepth(root,1);
        return result;
    }
};

简化版:

class Solution {
public:
    int result;
    void getDepth(TreeNode* node,int depth){
        result=depth>result?depth:result;
        if(node->left==nullptr&&node->right==nullptr)return ;
        if(node->left){
            getDepth(node->left,depth+1);
        }
        if(node->right){
            getDepth(node->right,depth+1);
        }
        return;
    }
    int maxDepth(TreeNode* root) {
        result=0;
        if(root==nullptr)return result;
        getDepth(root,1);
        return result;
    }
};

*代码递归中运用了回溯过程

正文:

递归代码:

class Solution {
public:
     int getDepth(TreeNode* node){
        if(node==NULL)return 0;
        int leftDepth=getDepth(node->left);
        if(leftDepth==-1)return -1;
        int rightDepth=getDepth(node->right);
        if(rightDepth==-1)return -1;
        return abs(leftDepth-rightDepth)>1?-1:1+max(leftDepth,rightDepth);
    }
    bool isBalanced(TreeNode* root) {
        return getDepth(root)==-1?false:true;
    }
};

*求高度,用迭代算法,回溯过程不能更好的利用,有浪费,不建议使用。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/784007.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号