Swift solution - recursive


  • 0
    class Solution {
        func buildTree(_ preorder: [Int], _ inorder: [Int]) -> TreeNode? {
            return helper(0, 0, inorder.count - 1, preorder, inorder)
        }
        
        private func helper(_ preStart: Int, _ inStart: Int, _ inEnd: Int, _ preorder: [Int], _ inorder: [Int]) -> TreeNode? {
            if preStart > preorder.count - 1 || inStart > inEnd {
                return nil
            }
            
            let root = TreeNode(preorder[preStart])
            var inIndex = 0
            
            for i in inStart...inEnd {
                if inorder[i] == root.val {
                    inIndex = i
                    break
                }
            }
            root.left = helper(preStart + 1, inStart, inIndex - 1, preorder, inorder)
            root.right = helper(preStart + inIndex - inStart + 1, inIndex + 1, inEnd, preorder, inorder)
            
            return root
        }
    }
    

Log in to reply
 

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