JAVA Easy Solution


  • 0
    J
    public class Solution {
        public TreeNode buildTree(int[] preorder, int[] inorder) {
            if (preorder == null || preorder.length == 0) return null;
            int len1 = preorder.length, len2 = inorder.length;
            return build(preorder, 0, len1 - 1, inorder, 0, len2 - 1);
        }
        
        private TreeNode build(int[] preorder, int startpre, int endpre, int[] inorder, int startin, int endin) {
            TreeNode root = new TreeNode(preorder[startpre]);
            if (startin == endin || startpre > endpre) {
                return root;
            }
            int mid = startin;
            while (mid <= endin && inorder[mid] != preorder[startpre]) {
                mid++;
            }
            
            if (mid > startin) {
                root.left = build(preorder, startpre + 1, endpre, inorder, startin, mid - 1);
            } 
            
            if (mid < endin) {
                root.right = build(preorder, startpre + mid - startin + 1, endpre, inorder, mid + 1, endin);
            }
            
            
            return root;
        }
    }

Log in to reply
 

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