📅  最后修改于: 2023-12-03 14:50:48.436000             🧑  作者: Mango
This question is a programming question asked in the ISRO (Indian Space Research Organisation) Computer Science 2018 exam.
Given a binary tree, the task is to print its nodes in level order traversal using Iterative method.
The input consists of a binary tree represented in the input list. Each element in the list represents a node with its left and right children. If the node has no children, the corresponding element is null
. The first element in the list is the root of the binary tree.
The output consists of the level order traversal of the binary tree in a list.
root = [3,9,20,null,null,15,7]
[3, 9, 20, 15, 7]
The level order traversal of a binary tree is performed using a queue. We start by pushing the root node into the queue. Then, we pop the first element from the queue and print it. Next, we push the left and right children of this node into the queue. We repeat this process until the queue is empty.
Here is the Python code to perform iterative level order traversal:
from collections import deque
def levelOrder(root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
result = []
queue = deque()
queue.append(root)
while queue:
level = []
size = len(queue)
for i in range(size):
node = queue.popleft()
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(level)
return result
The above code has time complexity O(n)
where n
is the number of nodes in the binary tree. The space complexity of the algorithm is also O(n)
since the queue can hold at most n
nodes (if the tree is a complete binary tree).