Java solution using recursive


  • 0
    I
    public class Solution {
        public TreeNode buildTree(int[] inorder, int[] postorder) {
            int length = inorder.length;
            if(length == 0) return null;
            Map<Integer, Integer> map = new HashMap<Integer, Integer>();
            for(int i = 0; i < length; i++) {
                map.put(inorder[i], i);
            }
            
            return build(inorder, postorder, 0, length - 1, 0, length - 1, map);
        }
        private TreeNode build(int[] inorder, int[] postorder, int instart, int inend, int poststart, int postend, Map<Integer, Integer> map) {
            if(instart > inend || poststart > postend) return null;
            TreeNode node = new TreeNode(postorder[postend]);
            if(instart == inend) return node;
            int mid = map.get(node.val);
            int length = mid - instart;
            node.left = build(inorder, postorder, instart, mid - 1, poststart, poststart + length - 1, map);
            node.right = build(inorder, postorder, mid + 1, inend, poststart + length, postend - 1, map);
            return node;
            
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.