We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent ae4dfa8 commit c8ac023Copy full SHA for c8ac023
construct-binary-tree-from-preorder-and-inorder-traversal/delight010.swift
@@ -0,0 +1,26 @@
1
+class Solution {
2
+ // Time O(N)
3
+ // Space O(N)
4
+ func buildTree(_ preorder: [Int], _ inorder: [Int]) -> TreeNode? {
5
+ if preorder.isEmpty {
6
+ return nil
7
+ }
8
+
9
+ let totalCount = preorder.count
10
+ let rootNode = TreeNode(preorder[0])
11
+ var rootIndex = 0
12
13
+ for (index, value) in inorder.enumerated() {
14
+ if value == rootNode.val {
15
+ rootIndex = index
16
+ break
17
18
19
20
+ rootNode.left = buildTree(Array(preorder[1..<rootIndex + 1]), Array(inorder[0..<rootIndex + 1]))
21
+ rootNode.right = buildTree(Array(preorder[1 + rootIndex..<totalCount]), Array(inorder[1 + rootIndex..<totalCount]))
22
23
+ return rootNode
24
25
+}
26
0 commit comments