I'm solving a question to check for a Balanced Binary Tree. It states that:
Given a binary tree, find if it is height balanced or not. A tree is height balanced if difference between heights of left and right subtrees is not more than one for all nodes of tree.
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.
Your Task: You don't need to take input. Just complete the function isBalanced() that takes root node as parameter and returns true, if the tree is balanced else returns false.
This is the following solution for the problem:
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)
Can anyone tell me what does the return l and r
do? What does using and
with return
do?