106. 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.

For example, given

inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

Solution

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

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