Grokking Tree Coding Patterns for Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
It's CONFUSING that the BoilerPlate for the Question isn't used in the Solution (9/26/23)

greenwald.juj

Sep 26, 2023

This is a little confusing since you expect that what's in the boiler plate here is suppose to be in the solution

Boiler Plate for Question

class Solution: def traverse(self, root): deq = deque() # TODO: Write your code here result = [list(sublist) for sublist in deq] return result

Solution - FOLLOWS SIMILAR FORMAT AS 'LEVEL ORDER TRAVERSAL' QUESTION

def traverse(root): result = deque() if root is None: return result queue = deque() queue.append(root) while queue: levelSize = len(queue) currentLevel = [] for _ in range(levelSize): currentNode = queue.popleft() # add the node to the current level currentLevel.append(currentNode.val) # insert the children of current node in the queue if currentNode.left: queue.append(currentNode.left) if currentNode.right: queue.append(currentNode.right) result.appendleft(currentLevel) return result

1

0

Comments
Comments