首页 > 其他 > 详细

Leetcode 110 平衡二叉树

时间:2020-12-02 00:03:57      阅读:26      评论:0      收藏:0      [点我收藏+]

Leetcode 110 平衡二叉树

数据结构定义:

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

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

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
    
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:true

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

输入:root = []
输出:true

自底向上写法:

class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null){
            return true;
        }
        return dfs(root) != -1;

    }
    private int dfs(TreeNode root){
        if(root == null){
            return 0;
        }
        int left = dfs(root.left);
        int right = dfs(root.right);
        if(left == -1 || right == -1 || Math.abs(left - right) > 1){
            return -1;
        }
        return Math.max(left,right) + 1;
    }
}

自顶向下:

class Solution {
    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }else {
            return Math.abs(height(root.left) - height(root.right)) <= 1
                    && isBalanced(root.left)
                    && isBalanced(root.right);
        }
    }

    private int height(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return Math.max(height(root.left), height(root.right)) + 1;
    }
}

Leetcode 110 平衡二叉树

原文:https://www.cnblogs.com/CodingXu-jie/p/14070684.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!