⬅ Previous Topic
Reverse Level Order Traversal of a Binary Tree using IterationNext Topic ⮕
Find Height of a Binary Tree⬅ Previous Topic
Reverse Level Order Traversal of a Binary Tree using IterationNext Topic ⮕
Find Height of a Binary Treeclass TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def reverseLevelOrder(root):
levels = []
def helper(node, level):
if not node:
return
if len(levels) == level:
levels.append([])
levels[level].append(node.val)
helper(node.left, level + 1)
helper(node.right, level + 1)
helper(root, 0)
result = []
for level in reversed(levels):
result.extend(level)
return result
# Example usage:
if __name__ == '__main__':
# Construct binary tree:
# 1
# / \
# 2 3
# / \ / \
# 4 5 6 7
root = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3, TreeNode(6), TreeNode(7)))
print(reverseLevelOrder(root))
⬅ Previous Topic
Reverse Level Order Traversal of a Binary Tree using IterationNext Topic ⮕
Find Height of a Binary TreeYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.