Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal

来源:互联网 发布:lg扫地机器人.知乎 编辑:程序博客网 时间:2024/06/06 02:34
/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    // postorder determines the root of a tree, inorder determines the left and right child of a tree    public TreeNode buildBTByInPost(int[] in, int is, int ie, int[] post, int ps, int pe, HashMap<Integer, Integer> inMap) {        if (ps > pe) return null;        if (ps == pe) return new TreeNode(post[pe]);                // the last element of a postorder is the root of a tree        // using hashmap to find the index of the postorder        int rootIdx = inMap.get(post[pe]);        TreeNode root = new TreeNode(post[pe]);                // build left and right child respectively        root.left = buildBTByInPost(in, is, rootIdx-1, post, ps, pe-(ie-rootIdx)-1, inMap);        root.right = buildBTByInPost(in, rootIdx+1, ie, post, pe-(ie-rootIdx), pe-1, inMap);        return root;    }        public TreeNode buildTree(int[] inorder, int[] postorder) {        if (inorder.length == 0 || postorder.length == 0) return null;                // put inorder into a hashmap so that we can find the index of a postorder in o(n)        HashMap<Integer, Integer> inMap = new HashMap<Integer, Integer>();        for (int i=0; i<inorder.length; i++)            inMap.put(inorder[i], i);        return buildBTByInPost(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1, inMap);    }}

0 0