平衡二叉树#
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| 示例 1:
给定二叉树 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回 true 。
示例 2:
给定二叉树 [1,2,2,3,3,null,null,4,4]
1
/ \
2 2
/ \
3 3
/ \
4 4
返回 false 。
|
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/balanced-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
递归步骤:
- 计算当前结点左右子树深度,不符合条件
return false - 递归左子树、递归右子树
计算子树最大深度:
- 左子树递归求高度
- 右子树递归求高度
- 比较,返回较大的,并+1
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
| /**
* 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
}
ld, rd := maxDepth(root.Left), maxDepth(root.Right)
if ld - rd < -1 || ld - rd > 1 {
return false
}
return isBalanced(root.Left) && isBalanced(root.Right)
}
func maxDepth(root *TreeNode) int {
if root == nil {
return 0
}
ld, rd := maxDepth(root.Left), maxDepth(root.Right)
if ld > rd {
return ld + 1
}
return rd + 1
}
// 执行用时 :12 ms, 在所有 Go 提交中击败了52.90%的用户
// 内存消耗 :5.7 MB, 在所有 Go 提交中击败了99.21%的用户
|
无