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.

【复杂度】

【思路】

【代码】

`/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    private int postEnd=0;    public TreeNode buildTree(int[] inorder, int[] postorder) {        postEnd=postorder.length-1;        return helper(0,inorder.length-1,inorder,postorder);    }    private TreeNode helper(int inStart,int inEnd,int[] inorder, int[] postorder){        //base case        if(inStart>inEnd)            return null;        TreeNode root=new TreeNode(postorder[postEnd--]);        int inMid=0;        for(int i=inStart;i<=inEnd;i++){            if(root.val==inorder[i]){                inMid=i;                break;            }        }        root.right=helper(inMid+1,inEnd,inorder,postorder);        root.left=helper(inStart,inMid-1,inorder,postorder);        return root;    }}`