Construct Binary Tree from Inorder and Postorder Traversal
Given inorder and postorder traversal of a tree, construct the binary tree.
Note: You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]Return the following binary tree:
3
/ \
9 20
/ \
15 7Explanation:
The Basics:
Inorder, postorder, and preorder are all flavors of Depth First Search. The difference between them is when the child nodes are visited relative to the root node.
Inorder is left, root, right Postorder is left, right, root Preorder is root, left, right
Note: outside of the context of this question, the order of the child nodes can be reversed. The thing that matters is when the root node is visited relative to the child nodes.
Observation 1:
If we reverse the postorder array, we end up with a preorder array (only root, right, left instead of root, left, right).
Observation 2:
The relative positions of the values in the inorder array can tell us whether a value appears on the left or right side of another value in the tree.
Strategy:
Reverse the postorder traversal to get a preorder traversal. If a value in the preorder traversal is on the right side of its previous value, the current value is the previous value's right child (because the preorder goes root, right, left and so the right node shows up immediately after the root and it keeps diving right). Otherwise, the current value might be the previous value's left child, but it might also be the left child of a grandparent or great-grandparent, and so we need to check up the tree until we either reach the root or reach a node that is still on the left of the current value.
Pseudo code:
Code:
Solution
What we get from those two fields (different order of elements).
Here is a solution.
Last updated
Was this helpful?