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.

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

Thinking:

/**
 * 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) {
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < inorder.length; i++){
            map.put(inorder[i], i);
        }
        return createTree(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1, map);
    }
    private static TreeNode createTree(int[] inorder, int inLow, int inHigh, int[] postorder, int postLow, int postHigh, Map<Integer, Integer> map){
        if(inLow > inHigh || postLow > postHigh) return null;
        int val = postorder[postHigh];
        TreeNode cur = new TreeNode(val);
        int pos = map.get(val);
        int len = inHigh - pos;
        cur.right = createTree(inorder, pos + 1, inHigh, postorder, postHigh - len, postHigh - 1, map);
        cur.left = createTree(inorder, inLow, pos - 1, postorder, postLow, postHigh - len - 1, map);
        return cur;
    }
}

二刷

有了前一题的结果,这一题写的比较顺畅。

/**
 * 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) {
        if(inorder == null || postorder == null) return null;
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < inorder.length; i++)
            map.put(inorder[i], i);
        return createTree(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1, map);
    }
    private TreeNode createTree(int[] inOrder, int iStart, int iEnd, int[] postOrder, int pStart, int pEnd, Map<Integer, Integer> map){
        if(iStart > iEnd || pStart > pEnd) return null;
        TreeNode node = new TreeNode(postOrder[pEnd]);
        int index = map.get(postOrder[pEnd]);
        int len = iEnd - index;
        node.left = createTree(inOrder, iStart, index - 1, postOrder, pStart, pEnd - len - 1, map);
        node.right = createTree(inOrder, index + 1, iEnd, postOrder, pEnd - len, pEnd - 1, map);
        return node;
    }
}