Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Construct Binary Tree from Preorder and Postorder Traversal in Python
Binary tree construction from preorder and postorder traversals is a fundamental algorithm problem. Given two traversal sequences, we can reconstruct the original binary tree using a stack-based approach.
Understanding the Problem
Given preorder traversal [1,2,4,5,3,6,7] and postorder traversal [4,5,2,6,7,3,1], we need to construct the binary tree. The preorder visits root first, while postorder visits root last.
Algorithm Steps
The stack-based algorithm works as follows:
- Create root node from first preorder element
- Use stack to track current path from root
- For each preorder element, create node and attach as left/right child
- Pop from stack when postorder element matches stack top
Implementation
class TreeNode:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def height(root):
if root is None:
return 0
else:
# Compute the height of left and right subtree
l_height = height(root.left)
r_height = height(root.right)
# Find the greater one, and return it
if l_height > r_height:
return l_height + 1
else:
return r_height + 1
def print_given_level(root, level):
if root is None:
return
if level == 1:
print(root.data, end=',')
elif level > 1:
print_given_level(root.left, level - 1)
print_given_level(root.right, level - 1)
def level_order(root):
print('[', end='')
h = height(root)
for i in range(1, h + 1):
print_given_level(root, i)
print(']')
class Solution(object):
def constructFromPrePost(self, pre, post):
"""
:type pre: List[int]
:type post: List[int]
:rtype: TreeNode
"""
ans = TreeNode(pre[0])
stack = [ans]
i = 1
j = 0
while i < len(pre) and j < len(post):
if stack[-1].data == post[j]:
j += 1
stack.pop(-1)
continue
node = TreeNode(pre[i])
if not stack[-1].left:
stack[-1].left = node
else:
stack[-1].right = node
stack.append(node)
i += 1
return ans
# Example usage
ob = Solution()
pre = [1, 2, 4, 5, 3, 6, 7]
post = [4, 5, 2, 6, 7, 3, 1]
tree = ob.constructFromPrePost(pre, post)
level_order(tree)
[1,2,3,4,5,6,7,]
How It Works
The algorithm uses a stack to maintain the current path from root to the node being processed. When the top of the stack matches the current postorder element, it means we've finished processing that subtree and can pop from the stack.
Key Points
- Preorder: Root ? Left ? Right (process root first)
- Postorder: Left ? Right ? Root (process root last)
- Stack: Tracks current path from root to current node
- Time Complexity: O(n) where n is number of nodes
- Space Complexity: O(n) for the stack
Conclusion
This stack-based approach efficiently constructs a binary tree from preorder and postorder traversals. The key insight is using the stack to track the current path and matching elements between traversals to determine when subtrees are complete.
