106. 从中序与后序遍历序列构造二叉树

同105

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    private Map<Integer, Integer> indexMap;
    public TreeNode myBuildTree(int[] inorder, int[] postorder, int inorder_left, int inorder_right, int postorder_left, int postorder_right) {
        if (postorder_left > postorder_right) return null;
        TreeNode root = new TreeNode(postorder[postorder_right]);
        int inorder_root = indexMap.get(postorder[postorder_right]);
        int element_size = inorder_root - inorder_left;
        root.left = myBuildTree(inorder, postorder, inorder_left, inorder_root - 1, postorder_left, postorder_left + element_size - 1); // 注意poster的范围
        root.right = myBuildTree(inorder, postorder, inorder_root + 1, inorder_right, postorder_left + element_size, postorder_right - 1); // 注意poster的范围
        return root;
    }
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        int n = inorder.length;
        indexMap = new HashMap<>();
        for (int i = 0; i < n; ++i) {
            indexMap.put(inorder[i], i);
        }
        return myBuildTree(inorder, postorder, 0, n - 1, 0, n - 1);
    }
}

你可能感兴趣的:(LeetCode,java,算法,数据结构,leetcode)