Skip to content

Commit abd1def

Browse files
committed
feat: Add solution for LeetCode problem 105
1 parent 5d0c37b commit abd1def

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
//
2+
// 105. Construct Binary Tree from Preorder and Inorder Traversal
3+
// https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/
4+
// Dale-Study
5+
//
6+
// Created by WhiteHyun on 2024/06/27.
7+
//
8+
9+
/**
10+
* Definition for a binary tree node.
11+
* public class TreeNode {
12+
* public var val: Int
13+
* public var left: TreeNode?
14+
* public var right: TreeNode?
15+
* public init() { self.val = 0; self.left = nil; self.right = nil; }
16+
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
17+
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
18+
* self.val = val
19+
* self.left = left
20+
* self.right = right
21+
* }
22+
* }
23+
*/
24+
class Solution {
25+
func buildTree(_ preorder: [Int], _ inorder: [Int]) -> TreeNode? {
26+
let indices: [Int: Int] = Dictionary(uniqueKeysWithValues: inorder.enumerated().map { ($0.element, $0.offset) })
27+
28+
var preorderIndex = 0
29+
30+
func build(_ left: Int, _ right: Int) -> TreeNode? {
31+
if left > right { return nil }
32+
33+
let rootValue = preorder[preorderIndex]
34+
preorderIndex += 1
35+
let root = TreeNode(rootValue)
36+
37+
let mid = indices[rootValue]!
38+
39+
root.left = build(left, mid - 1)
40+
root.right = build(mid + 1, right)
41+
42+
return root
43+
}
44+
45+
return build(0, inorder.count - 1)
46+
}
47+
}

0 commit comments

Comments
 (0)