我正在解决一个问题,以检查平衡二叉树。它指出:
给出一棵二叉树,查找它是否高度平衡。 如果树的所有节点的左右子树的高度之差不超过一棵,则树是高度平衡的。
Example 1:
Input:
1
/
2
\
3
Output: 0
Explanation: The max difference in height
of left subtree and right subtree is 2,
which is greater than 1. Hence unbalanced
Example 2:
Input:
10
/ \
20 30
/ \
40 60
Output: 1
Explanation: The max difference in height
of left subtree and right subtree is 1.
Hence balanced.
您的任务: 您不需要输入。只需完成以根节点为参数并返回true的isBalanced()函数,如果树是平衡的,则返回false。
这是针对该问题的以下解决方案:
class Height:
def __init__(self):
self.height = 0
# helper function to check if binary
# tree is height balanced
def isBalancedUtil(root, height):
# lh and rh to store height of
# left and right subtree
lh = Height()
rh = Height()
# Base condition when tree is
# empty return true
if root is None:
return True
# l and r are used to check if left
# and right subtree are balanced
l = isBalancedUtil(root.left, lh)
r = isBalancedUtil(root.right, rh)
# height of tree is maximum of
# left subtree height and
# right subtree height plus 1
height.height = max(lh.height, rh.height) + 1
if abs(lh.height - rh.height) <= 1:
return l and r
# if we reach here then the tree
# is not balanced
return False
def isBalanced(root):
# to store the height of tree during traversal
height = Height()
return isBalancedUtil(root,height)
有人可以告诉我return l and r
做什么吗?将and
与return
一起使用会做什么?
答案 0 :(得分:0)
它使用逻辑函数r AND l
定义输出。
TRUE AND TRUE -> TRUE
TRUE AND FALSE -> FALSE
FALSE AND TRUE -> FALSE
FALSE AND FALSE -> FALSE
答案 1 :(得分:0)
return l and r
的意思是return (l and r)
。它将返回(l and r)
的求值,如果l
和r
为true
且为false
,则返回true。