Skip to content

Commit 5952468

Browse files
committed
110.平衡二叉树
1 parent ee7c2e1 commit 5952468

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
- [101.对称二叉树](leetcode/101.go)
2626
- [104.二叉树的最大深度](leetcode/104.go)
2727
- [108.将有序数组转换为二叉搜索树](leetcode/108.go)
28+
- [110.平衡二叉树](leetcode/110.go)
2829
- [111.二叉树的最小深度](leetcode/111.go)
2930
- [112.路径总和](leetcode/112.go)
3031
- [118.杨辉三角](leetcode/118.go)

leetcode/110.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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+
}

0 commit comments

Comments
 (0)