LeetCode - Blind 75 - Construct Binary Tree from Preorder and Inorder Traversal

The Problem Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree. Examples Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] Output: [3,9,20,null,null,15,7] Input: preorder = [-1], inorder = [-1] Output: [-1] Constraints 1 <= preorder.length <= 3000 inorder.length == preorder.length -3000 <= preorder[i], inorder[i] <= 3000 preorder and inorder consist of unique values. Each value of inorder also appears in preorder. preorder is guaranteed to be the preorder traversal of the tree. inorder is guaranteed to be the inorder traversal of the tree. Depth First Search Solution func buildTree(_ preorder: [Int], _ inorder: [Int]) -> TreeNode? { if preorder.isEmpty || inorder.isEmpty { return nil } let rootVal = preorder[0] let root = TreeNode(rootVal) guard let mid = inorder.firstIndex(of: rootVal) else { return nil } if mid > 0 { root.left = buildTree(Array(preorder[1...mid]), Array(inorder[0..<mid])) } if mid < inorder.count - 1 { root.right = buildTree(Array(preorder[mid + 1..<preorder.count]), Array(inorder[mid + 1..<inorder.count])) } return root } Explanation We can solve this problem by understanding how preorder and inorder traversal work. ...

January 23, 2025 · 3 min · Dmytro Chumakov