110. 平衡二叉树

平衡二叉树

题目描述:

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

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

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 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

思路:

自底向上判断,判断这个结点的两个子结点的高度差是否大于1,大于1就说明不是平衡二叉树

代码:

func isBalanced(root *TreeNode) bool {
    if root ==nil{
        return true
    }
    return heigth(root)>=0
}
func heigth(root *TreeNode) int{
    if root==nil{
        return 0
    }
    leftheight := heigth(root.Left)
    rightheight := heigth(root.Right)
    if abs(leftheight-rightheight)>=2{
        return -9999
    }
    return max(leftheight,rightheight)+1
}
func max(a,b int)int{
    if a>b{
        return a
    }else{
        return b
    }
}
func abs(a int)int {
    if a<0{
        return -1*a
    }else{
        return a
    }
}

代码效率:

执行用时:8 ms, 在所有 Go 提交中击败了85.62%的用户
内存消耗:5.7 MB, 在所有 Go 提交中击败了99.51%的用户