Skip to content

Commit a0c2edd

Browse files
authored
Merge pull request #1964 from delight010/main
[SeongA] WEEK 15 solutions
2 parents e16f4cf + f43c4fb commit a0c2edd

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution {
2+
// Time O(N^2)
3+
// Space O(N)
4+
func buildTree(_ preorder: [Int], _ inorder: [Int]) -> TreeNode? {
5+
return buildTree(preorder[...], inorder[...])
6+
}
7+
8+
func buildTree(_ preorder: ArraySlice<Int>, _ inorder: ArraySlice<Int>) -> TreeNode? {
9+
if preorder.isEmpty {
10+
return nil
11+
}
12+
13+
let rootNode = TreeNode(preorder.first!)
14+
var rootIndex = 0
15+
16+
for (index, value) in inorder.enumerated() {
17+
if value == rootNode.val {
18+
rootIndex = index
19+
break
20+
}
21+
}
22+
rootNode.left = buildTree(preorder[preorder.startIndex + 1..<preorder.startIndex + rootIndex + 1], inorder[inorder.startIndex..<inorder.startIndex + rootIndex])
23+
rootNode.right = buildTree(preorder[preorder.startIndex + 1 + rootIndex..<preorder.endIndex], inorder[inorder.startIndex + 1 + rootIndex..<inorder.endIndex])
24+
25+
return rootNode
26+
}
27+
}
28+
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution {
2+
// Time O(M * N)
3+
// Space O(M + N)
4+
func isSubtree(_ root: TreeNode?, _ subRoot: TreeNode?) -> Bool {
5+
if let root = root, let subRoot = subRoot {
6+
return dfs(root, subRoot) || isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot)
7+
}
8+
9+
return root == nil && subRoot == nil
10+
}
11+
12+
private func dfs(_ root: TreeNode?, subRoot: TreeNode?) -> Bool {
13+
if let root = root, let subRoot = subRoot {
14+
return root.val == subRoot.val && dfs(root.left, subRoot.left) && dfs(root.right, subRoot.right)
15+
}
16+
17+
return root == nil && subRoot == nil
18+
}
19+
}
20+

0 commit comments

Comments
 (0)