Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

PYTHON 3 PLEASE FOLLOW INSTRUCTIONS COMPLETE CODE Problem : Complete the function isBalanced() to take in a root node of a binary tree and return

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, val): self.left = None self.right = None self.val = val

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

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

if retl and retr: return abs(leftroot-rightroot) < 2, h else: return False, h 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

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

More Books

Students also viewed these Databases questions

Question

(2) FA W 30 m FX M FA 300

Answered: 1 week ago

Question

Discuss the different types of leadership

Answered: 1 week ago

Question

Write a note on Organisation manuals

Answered: 1 week ago

Question

Define Scientific Management

Answered: 1 week ago

Question

Explain budgetary Control

Answered: 1 week ago

Question

12-5 How will MIS help my career?

Answered: 1 week ago