题目
输入一棵二叉树的根节点,判断该树是不是平衡二叉树。
如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
示例 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 。
限制:
1 <= 树的结点个数 <= 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof
解题思路
1、什么是平衡二叉树
- 如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
2、求二叉树的深度
- 递归求二叉树的深度,具体解法和思路解释请看 面试题55 - I - 二叉树的深度
3、通过递归计算每一个节点左右子树的深度,
- 利用 && 的短路特性判断,相差都不超过1则为平衡二叉树,否则该二叉树不是平衡二叉树
代码
–执行时间:4 ms --消耗内存:5.7 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
}
//获取节点的左右子树的深度(首次为根节点)
Left,Right:=maxDepth(root.Left),maxDepth(root.Right)
//相差不超过1
if math.Abs(float64(Left)-float64(Right))<=1{
//递归计算其他节点的左右子树的深度是否超过1
return isBalanced(root.Left) && isBalanced(root.Right)
}
//超过1,不是平衡二叉树
return false
}
//递归获取二叉树的深度
func maxDepth(root *TreeNode) int {
if root==nil{
return 0
}
Left:=maxDepth(root.Left)
Right:=maxDepth(root.Right)
return max(Left,Right)+1
}
func max(a,b int)int{
if a>b{
return a
}
return b
}