I am trying to solve the Leetcode problem: 102. Binary Tree Level Order Traversal and hit a snag. My code below does not give the correct output and I have been trying to figure out what is the issue since it is not appending the last level in the tree. I would appreciate it someone can assist in making this code work.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
while not root:
return []
queue = [root]
result = [[queue[0].val]]
while queue:
nodes = queue
level_nodes = []
temp = []
for node in nodes:
level = queue.pop(0)
if node.left:
level_nodes.append(level.left.val)
temp.append(node.left)
if node.right:
level_nodes.append(level.right.val)
temp.append(node.right)
queue = temp
result.append(level_nodes)
return result
Input: root = [3,9,20,null,null,15,7]
Expected Output: [[3],[9,20],[15,7]]
Output I am getting: [[3],[9,20],[]]
Reference: https://leetcode.com/problems/binary-tree-level-order-traversal/description/