Construct Binary Tree from Inorder and Postorder Traversal

题目地址:
https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/description/

题目:
Given inorder and postorder traversal of a tree, construct the binary tree.

解题思路:
这道题还是用用map+recursion的解法。

代码:

public TreeNode buildTree(int[] inorder, int[] postorder) {
    Map<Integer, Integer> map = new HashMap<>();
    for(int i = 0; i <= inorder.length - 1; i++){
        map.put(inorder[i], i);
    }
    return helper(map, inorder, postorder, 0, inorder.length - 1, 0, postorder.length - 1);
}

private TreeNode helper(Map<Integer, Integer> map , int[] inorder, int[] postorder, int inLeftBound, int inRightBound, int postLeftBound, int postRightBound){
    if(inLeftBound > inRightBound || postLeftBound > postRightBound){
        return null;
    }
    int rootValue = postorder[postRightBound];
    int inRootIndex = map.get(rootValue);
    int leftRangeLen = inRootIndex - inLeftBound;
    int rightRangeLen = inRightBound - inRootIndex;
    TreeNode root = new TreeNode(rootValue);
    root.left = helper(map, inorder, postorder, inLeftBound, inRootIndex - 1, postLeftBound, postRightBound - rightRangeLen - 1);
    root.right = helper(map, inorder, postorder, inRootIndex + 1, inRightBound, postLeftBound + leftRangeLen, postRightBound - 1);
    return root;
}





Comments

Popular Posts