Java recursive solution using map


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

Log in to reply
 

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