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
| // @Title: 平衡二叉树 (Balanced Binary Tree)
// @Author: 15816537946@163.com
// @Date: 2019-11-23 17:54:23
// @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 {
_, isBalanced := recur(root)
return isBalanced
}
func recur(root *TreeNode) (int, bool) {
if root == nil {
return 0, true
}
lt, lBalanced := recur(root.Left)
rt, rBalanced := recur(root.Right)
if lBalanced && rBalanced &&
-1 <= lt-rt && lt-rt <= 1 {
return 1 + max(lt, rt), true
}
return 0, false
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
|