Tree: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.

  public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
     TreeNode(int x) { val = x; }
  } 
  public TreeNode buildTree(int[] inorder, int[] postorder) {
        if (inorder==null||postorder==null||inorder.length==0||postorder.length==0||inorder.length!=postorder.length) {
            return null;
        }
        HashMap hashMap = new HashMap();
        for (int i = 0; i < inorder.length; i++) {
            hashMap.put(inorder[i], i);
        }
        return inPos(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1, hashMap);
    }
   private TreeNode inPos(int[] in,int ni,int nj,int[] pos,int si,int sj,HashMap hashMap) {
        if (si>sj) {
            return null;
        }
        int index = hashMap.get(pos[sj]);
        TreeNode node = new TreeNode(pos[sj]);
        node.left = inPos(in, ni, index-1, pos, si, si+index-ni-1, hashMap);
        node.right = inPos(in, index+1, nj, pos, si+index-ni, sj-1, hashMap);
        return node;
  }

你可能感兴趣的:(Tree:Construct Binary Tree from Inorder and Postorder Traversal)