微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

“返回x和y”是什么意思?

如何解决“返回x和y”是什么意思?

我正在解决一个问题,以检查平衡二叉树。它指出:

给出一棵二叉树,查找它是否高度平衡。 如果树的所有节点的左右子树的高度之差不超过一棵,则树是高度平衡的。

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做什么吗?将andreturn一起使用会做什么?

解决方法

它使用逻辑函数r AND l定义输出。

TRUE AND TRUE -> TRUE
TRUE AND FALSE -> FALSE
FALSE AND TRUE -> FALSE
FALSE AND FALSE -> FALSE
,

return l and r的意思是return (l and r)。它将返回(l and r)的求值,如果lrtrue且为false,则返回true。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。