Construct Binary Tree from Preorder and Inorder Traversal Java

来源:互联网 发布:pc6下载站 mac 编辑:程序博客网 时间:2024/06/02 06:08

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

Key to Solve: Recursion + HashMap(Key: Inorder's Node, Value: position)
    Preorder: we can see the top Root is 1st element of Preorder, and so on
    Inorder: the elements before the root are belong to left subtree
             after the root are belong to right subtree
    The split left and right subtree base on  value of Preorder
    and position of inorder

public class Solution {    public TreeNode buildTree(int[] preorder, int[] inorder) {  if(preorder.length==0 || inorder.length==0) return null;        HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();        for(int i=0;i<inorder.length;i++){            map.put(inorder[i],i);        }        return helperRecur(preorder,inorder,0,preorder.length-1,0,inorder.length-1,map);    }    private TreeNode helperRecur(int[] preorder, int[] inorder, int preL, int preR,                               int inL, int inR, HashMap<Integer,Integer> map){        if(preL>preR || inL>inR){            return  null;        }        TreeNode root=new TreeNode(preorder[preL]);        int rootIndex=map.get(root.val);        int distance=rootIndex-inL;        root.left=helperRecur(preorder,inorder,preL+1,preL+distance,inL,rootIndex-1,map);        root.right=helperRecur(preorder,inorder,preL+distance+1,preR,rootIndex+1,inR,map);        return root;    }}


0 0