/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isBalanced(root *TreeNode) bool {
if root == nil {
return true
}
return math.Abs(float64(height(root.Left) - height(root.Right))) <= 1 && isBalanced(root.Left) && isBalanced(root.Right)
}
func height(node *TreeNode) int {
if node == nil {
return 0
}
return max(height(node.Left), height(node.Right)) + 1
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
# 计算节点高度
def height(root: TreeNode):
if not root:
return 0
return max(height(root.left), height(root.right)) + 1
if not root:
return True
return self.isBalanced(root.left) and self.isBalanced(root.right) and abs(height(root.left) - height(root.right)) <= 1