Algorithm Steps
- If the binary tree is empty, return an empty result.
- Initialize an empty
queue
and push theroot
node onto it. - Initialize an empty
stack
. - While the
queue
is not empty, dequeue a node from the front, push it onto thestack
, then enqueue itsright
child (if it exists) followed by itsleft
child (if it exists). - Once the
queue
is empty, pop all nodes from thestack
and record their values. This produces the reverse level order traversal.
Reverse Level Order Traversal of a Binary Tree using Iteration - Code Examples Code
Python
Java
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def reverseLevelOrder(root):
if not root:
return []
from collections import deque
queue = deque([root])
stack = []
while queue:
node = queue.popleft()
stack.append(node)
if node.right:
queue.append(node.right)
if node.left:
queue.append(node.left)
result = []
while stack:
result.append(stack.pop().val)
return result
if __name__ == '__main__':
# Construct binary tree:
# 1
# / \
# 2 3
# / \
# 4 5
root = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3))
print(reverseLevelOrder(root))