Reconstructing a Tree from Postorder Traversal
Yes, it is possible to reconstruct a tree if you have just the postorder traversal. However, there are some constraints and assumptions:
- The tree is a binary tree (each node has at most two children).
- The postorder traversal is a sequence of node values.
Algorithm
The algorithm to reconstruct a binary tree from its postorder traversal is as follows:
- Identify the root node: The last element in the postorder traversal is the root node.
- Find the left and right subtrees: Iterate through the postorder traversal from left to right. The elements before the root node are part of the left subtree, and the elements after the root node are part of the right subtree.
- Recursively reconstruct the left and right subtrees: Apply the same process to the left and right subtrees.
Example
Suppose we have the following postorder traversal: [4, 5, 2, 6, 7, 3, 1]
- Identify the root node: The last element is
1, which is the root node.
- Find the left and right subtrees: The elements before
1 are [4, 5, 2, 6, 7, 3]. We need to find the boundary between the left and right subtrees.
- Find the boundary: Assume the tree is not empty and the root of the right subtree is greater than the root of the left subtree. Find the first element greater than the root node (
1) in the postorder traversal. In this case, there is no element greater than 1, so we assume the right subtree is empty.
- Recursively reconstruct the left subtree: Apply the same process to the left subtree
[4, 5, 2, 6, 7, 3]. The root node of the left subtree is 3, and the left and right subtrees are [4, 5, 2] and [6, 7], respectively.
Code
Here is a Python implementation of the algorithm:
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def constructFromPostorder(postorder):
if not postorder:
return None
root = TreeNode(postorder[-1])
if len(postorder) == 1:
return root
# Find the boundary between the left and right subtrees
i = len(postorder) - 2
while i >= 0 and postorder[i] > root.val:
i -= 1
# Recursively reconstruct the left and right subtrees
root.left = constructFromPostorder(postorder[:i+1])
root.right = constructFromPostorder(postorder[i+1:-1])
return root
def printTree(node, level=0):
if node is not None:
printTree(node.right, level + 1)
print(' ' * 4 * level + '->', node.val)
printTree(node.left, level + 1)
# Example usage
postorder = [4, 5, 2, 6, 7, 3, 1]
root = constructFromPostorder(postorder)
printTree(root)
This code defines a TreeNode class and a constructFromPostorder function to reconstruct the binary tree from its postorder traversal. The printTree function is used to print the reconstructed tree.
Note that this implementation assumes that the input postorder traversal is valid and corresponds to a binary tree. If the input is invalid, the function may not work correctly.