Sunday, December 28, 2014

Construct Binary Tree from Inorder and Postorder Traversal (LeetCode Array)

Question:  Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.

Idea: The last element of the postorder is the root. So we construct the tree from the end to the beginning of the postorder traversal in the root, root.right, root.left sequence. In the inorder traversal, we can search the root's position, assume the position is x. The the right half (x+1->end) is the right substree, which is the root of root.right. The same for the left substree. Keep constructing the substrees recursively.

Time: O(n^2) (the search root's position takes O(n), for each of the node).
Space: O(lgn)

Code:
 public class Solution {  
   private int postIndex;  
   public TreeNode buildTree(int[] inorder, int[] postorder) {  
     postIndex=postorder.length-1;  
     return dfs(inorder,postorder,0,inorder.length-1);  
   }  
   public int findIndex(int[] arr,int start,int end,int target)  
   {  
     for(int i=start;i<=end;i++)  
     {  
       if(arr[i]==target)  
         return i;  
     }  
     return -1;  
   }  
   public TreeNode dfs(int[] inorder,int[] postorder,int inStart,int inEnd)  
   {  
     if(inStart>inEnd)  
       return null;  
     TreeNode root=new TreeNode(postorder[postIndex]);  
     int splitPos=findIndex(inorder,inStart,inEnd,root.val);  
     postIndex--;  
     root.right=dfs(inorder,postorder,splitPos+1,inEnd);  
     root.left=dfs(inorder,postorder,inStart,splitPos-1);  
     return root;  
   }  
 }  


No comments:

Post a Comment