File tree Expand file tree Collapse file tree 2 files changed +30
-0
lines changed Expand file tree Collapse file tree 2 files changed +30
-0
lines changed Original file line number Diff line number Diff line change 25
25
- [ 101.对称二叉树] ( leetcode/101.go )
26
26
- [ 104.二叉树的最大深度] ( leetcode/104.go )
27
27
- [ 108.将有序数组转换为二叉搜索树] ( leetcode/108.go )
28
+ - [ 110.平衡二叉树] ( leetcode/110.go )
28
29
- [ 111.二叉树的最小深度] ( leetcode/111.go )
29
30
- [ 112.路径总和] ( leetcode/112.go )
30
31
- [ 118.杨辉三角] ( leetcode/118.go )
Original file line number Diff line number Diff line change
1
+ package leetcode
2
+
3
+ import "math"
4
+
5
+ //给定一个二叉树,判断它是否是高度平衡的二叉树。
6
+ //本题中,一棵高度平衡二叉树定义为:
7
+ //一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
8
+
9
+ func isBalanced (root * TreeNode ) bool {
10
+ if root == nil {
11
+ return true
12
+ }
13
+ var getDepth func (root * TreeNode ) int
14
+ getDepth = func (root * TreeNode ) int {
15
+ if root == nil {
16
+ return 0
17
+ }
18
+ left := getDepth (root .Left )
19
+ right := getDepth (root .Right )
20
+ //返回节点左右子树的最大深度+1
21
+ return max (left , right ) + 1
22
+ }
23
+
24
+ if math .Abs (float64 (getDepth (root .Left )- getDepth (root .Right ))) > 1 {
25
+ return false
26
+ }
27
+ // 左右子树都是平衡二叉树
28
+ return isBalanced (root .Left ) && isBalanced (root .Right )
29
+ }
You can’t perform that action at this time.
0 commit comments