Construct Binary Tree from Inorder and Postorder Traversal
Given inorder and postorder traversal of a tree, construct the binary tree.
Analysis
This problem can be illustrated by using a simple example.
inorder: 4 2 5 (1) 6 7 3 8 postorder: 4 5 2 6 7 8 3 (1)
From the postorder array, we know that last element is the root. We can find the root in inorder array. Then we can identify the left and right subtrees of the root from inorder array.
Using the length of left subtree, we can identify left and right subtrees in postorder array. Recursively, we can build up the tree.
For this example, the constructed tree is:
Java Solution
public TreeNode buildTree(int[] inorder, int[] postorder) { int inStart = 0; int inEnd = inorder.length  1; int postStart = 0; int postEnd = postorder.length  1; return buildTree(inorder, inStart, inEnd, postorder, postStart, postEnd); } public TreeNode buildTree(int[] inorder, int inStart, int inEnd, int[] postorder, int postStart, int postEnd) { if (inStart > inEnd  postStart > postEnd) return null; int rootValue = postorder[postEnd]; TreeNode root = new TreeNode(rootValue); int k = 0; for (int i = 0; i < inorder.length; i++) { if (inorder[i] == rootValue) { k = i; break; } } root.left = buildTree(inorder, inStart, k  1, postorder, postStart, postStart + k  (inStart + 1)); // Becuase k is not the length, it it need to (inStart+1) to get the length root.right = buildTree(inorder, k + 1, inEnd, postorder, postStart + k inStart, postEnd  1); // postStart+kinStart = postStart+k(inStart+1) +1 return root; } 
<pre><code> String foo = "bar"; </code></pre>

Darewreck

Matias SM

Mohamed Yakout

DivyaJyoti Rajdev

Zheyu Jin

Burhan COKCA

blah

F

Taras

Amritesh

Guest