LeetCode – Construct Binary Tree from Preorder and Inorder Traversal (Java)
Given preorder and inorder traversal of a tree, construct the binary tree.
Analysis
Consider the following example:
inorder: 4 2 5 (1) 6 7 3 8 preorder: (1) 2 4 5 3 7 6 8
From the preorder array, we know that first 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 preorder array. Recursively, we can build up the tree.
For this example, the constructed tree is:
Java Solution
public TreeNode buildTree(int[] preorder, int[] inorder) { int preStart = 0; int preEnd = preorder.length1; int inStart = 0; int inEnd = inorder.length1; return construct(preorder, preStart, preEnd, inorder, inStart, inEnd); } public TreeNode construct(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd){ if(preStart>preEndinStart>inEnd){ return null; } int val = preorder[preStart]; TreeNode p = new TreeNode(val); //find parent element index from inorder int k=0; for(int i=0; i<inorder.length; i++){ if(val == inorder[i]){ k=i; break; } } p.left = construct(preorder, preStart+1, preStart+(kinStart), inorder, inStart, k1); p.right= construct(preorder, preStart+(kinStart)+1, preEnd, inorder, k+1 , inEnd); return p; } 
<pre><code> String foo = "bar"; </code></pre>

Madhuri

Ram Anvesh Reddy

dpp

Sherif E. Saleh