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.

后续遍历 根节点在最后一个元素

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if (postorder == null || inorder == null) {
            return null;
        }
        int postLen = postorder.length;
        int inLen = inorder.length;
        if (postLen == 0 || inLen == 0) {
            return null;
        }

        return constructTree(postorder, 0, postLen - 1, inorder, 0, inLen - 1);
    }
    
    public static TreeNode constructTree(int[] postorder, int postStart, int postEnd,
            int[] inorder, int inStart, int inEnd) {
        int rootVal = postorder[postEnd];
        TreeNode root = new TreeNode(rootVal);
        root.left = null;
        root.right = null;
        
        if(postStart == postEnd && postorder[postStart] == inorder[inStart]){
            return root;
        }
        
        int i = inStart;
        for(; i <= inEnd; i++){
            if(inorder[i] == rootVal){
                break;
            }
        }
        int leftLen = i - inStart;
        // 如果左子树不为空
        if(leftLen > 0){
            root.left = constructTree(postorder, postStart, postStart + leftLen - 1,
                    inorder, inStart, i - 1);
        }
        // 如果右子树不为空
        if(inEnd > i){
            root.right = constructTree(postorder, postStart + leftLen, postEnd - 1,
                    inorder, i + 1, inEnd);
        }
        return root;
    }
}
原文地址:https://www.cnblogs.com/RazerLu/p/3545285.html