给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过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 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/balanced-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
_______________________________________________________________________________________________
思路:
先分别计算每个节点左右子树的深度,然后进行比较得出结果:
python实现:
class Solution:
#主调函数,返回结果
def isBalanced(self, root: TreeNode) -> bool:
if not root:
return True
return self.run(root)
#根据左右子树的深度判断是否为完全平衡二叉树
def run(self,root:TreeNode):
if not root:
return True
l = self.getDepth(root.left)
r = self.getDepth(root.right)
if abs(l-r)>1:
return False
return self.run(root.left) and self.run(root.right)
#得到每棵树的深度
def getDepth(self,root:TreeNode):
if not root:
return 0
l = self.getDepth(root.left)
r = self.getDepth(root.right)
return max(l,r)+1
实例代码中有关于python类的全局变量的用法,值得学习:
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
#类属性res
self.res = True
def helper(root):
#剪枝:
if self.res == False: return 0
if not root: return 0
left = helper(root.left) + 1
right = helper(root.right) + 1
if abs(left - right) > 1:
#直接修改类属性
self.res = False
return max(left,right)
helper(root)
return self.res
另一种方法更巧一些:
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
return self.recur(root) != -1
def recur(self, root):
if not root: return 0
left = self.recur(root.left)
#-1 标记左子树是否为完全平衡时
if left == -1: return -1
right = self.recur(root.right)
#-1 标记右子树是否为完全平衡树
if right == -1: return -1
#当为平衡树时,返回深度,不为平衡树时,返回-1
return max(left, right) + 1 if abs(left - right) < 2 else -1
个人觉得前两种好理解,思维方式很直观。
go实现:
func isBalanced(root *TreeNode) bool {
max := 0
Run(&max,root)
if max > 1 {
return false
}
return true
}
func Run(max *int,root *TreeNode) int {
if root == nil {
return 0
}
l := Run(max,root.Left)
r := Run(max,root.Right)
sub := 0
if l<r {
sub = r-l
} else {
sub = l-r
}
*max = Max(sub,*max)
return Max(l,r) + 1
}
func Max(a,b int) int {
if a>b {
return a
}
return b
}