Enrollments closing soon for Post Graduate Certificate Program in Applied Data Science & AI By IIT Roorkee | 3 Seats Left
Apply NowLogin using Social Account
     Continue with GoogleLogin using your credentials
Given the root of a binary tree, display the node values at each level. Node values for all levels should be displayed on separate lines. Let’s take a look at the below binary tree.
Level order traversal for this tree should look like:
100
50, 200
25, 75, 350
Runtime complexity: Linear, O(n)
Memory Complexity: Linear, O(n)
Example:
Input: Tree([100, [50, 25, 75], [200, None, 350]])
Output: [[100], [50, 200], [25, 75, 350]]
Input: Tree1([10, [5, [3, 2, 4], 7], [20, 15, 35]])
Output: [[10], [5, 20], [3, 7, 15, 35], [2, 4]]
Constraints:
level_order_traversal
You need to create a function with the following signature that should return an array of array. The first elements of the array would be an array containing only the top element and the last element of this array would be the array containing leaf nodes:
def level_order_traversal(root):
result = ""
#TODO: Write - Your - Code
return result
Please create the Tree using the following code:
class Tree:
def __str__(self):
if self.left or self.right:
return "[%s, %s, %s]" % (self.value, self.left, self.right)
else:
return "%s" % (self.value)
def __repr__(self):
return str(self)
def __init__(self, arr):
self.left = None
self.right = None
if type(arr) is list:
self.value = arr[0]
if arr[1]:
self.left = Tree(arr[1])
if arr[2]:
self.right = Tree(arr[2])
else:
self.value = arr
To create the tree shown in the below image, call:
Tree([100, [50, 25, 75], [200, None, 350]])
Taking you to the next exercise in seconds...
Want to create exercises like this yourself? Click here.
No hints are availble for this assesment
Note - Having trouble with the assessment engine? Follow the steps listed here
Loading comments...