Simple solution with cache


  • 0
    W
    public class Solution {
        public TreeNode buildTree(int[] preorder, int[] inorder) {
            final int pLen, iLen;
            
            if (preorder == null || inorder == null 
                || (pLen = preorder.length) == 0 || (iLen = inorder.length) == 0 || pLen != iLen) {
                return null;
            }
            
            final Map<Integer, Integer> map = new HashMap<>();
            
            for (int i = 0; i < iLen; ++i) {
                map.put(inorder[i], i);
            }
            
            final TreeNode head = help(preorder, map, 0, 0, iLen - 1);
            
            return head;
        }
        
        private TreeNode help(final int[] preorder, final Map<Integer, Integer> map,  int pStart, int iStart, int iEnd) {
            if (iStart > iEnd) {
                return null;
            }
            
            int cur = preorder[pStart];
            TreeNode node = new TreeNode(cur);
            int iIndex = map.get(cur);
            
            node.left = help(preorder, map, pStart + 1, iStart, iIndex - 1);
            node.right = help(preorder, map, pStart + iIndex - iStart + 1, iIndex + 1, iEnd);
            
            return node;
        }
    }
    

Log in to reply
 

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