Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

PYTHON 3 PLEASE FOLLOW INSTRUCTIONS COMPLETE CODE Problem : Complete the functio

ID: 3712433 • Letter: P

Question

PYTHON 3 PLEASE FOLLOW INSTRUCTIONS

COMPLETE CODE

Problem : Complete the function isBalanced() to take in a root node of a binary tree and return True if the tree is balanced, False otherwise.

Code:

class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
  
def isBalanced(root):
# TODO

root = Node(7)
root.left = Node(4)
root.left.left = Node(1)
root.left.right = Node(5)
"""
7
/
4 (NOT BALANCED)
/   
1 5
"""
print(isBalanced(root)) # has to print False

root.right = Node(10)
root.right.right = Node(13)
"""
7
/
4 10 (BALANCED)
/
1 5 13
"""
print(isBalanced(root)) # must print True

root.left.left.left = Node(0)
root.left.right = None
"""
7
/
4 10 (NOT BALANCED)
/
1 13
/
0
"""
print(isBalanced(root)) # must print False

Explanation / Answer

class Node:
def __init__(self, val):
self.left = None
self.right = None
self.val = val

def isBalanced(root):
ret, h = isBalanced_helper(root)
return ret

def isBalanced_helper(root):
if not root:
return True, 0
else:
retl, hl = isBalanced_helper(root.left)
retr, hr = isBalanced_helper(root.right)
h = max(hr, hl)+1

if retl and retr:
return abs(hl-hr) < 2, h
else:
return False, h