1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// @Title: 平衡二叉树 (平衡二叉树 LCOF)
// @Author: 15816537946@163.com
// @Date: 2022-02-18 23:36:10
// @Runtime: 8 ms
// @Memory: 5.5 MB
/**
 * 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 abs(height(root.Left)-height(root.Right)) <=1 && isBalanced(root.Left) && isBalanced(root.Right)
}

func height(root *TreeNode) int {
    if root == nil {
        return 0 
    }
    return max(height(root.Left),height(root.Right))+1
}

func max(x,y int) int {
    if x > y {
        return x
    }
    return y
}

func abs(x int) int {
    if x < 0 {
        return -1 *x
    }
    return x
}