forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.swift
40 lines (38 loc) · 977 Bytes
/
Solution.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/* class TreeNode {
* var val: Int
* var left: TreeNode?
* var right: TreeNode?
*
* init(_ val: Int, _ left: TreeNode? = nil, _ right: TreeNode? = nil) {
* self.val = val
* self.left = left
* self.right = right
* }
* }
*/
class Solution {
func checkSubTree(_ t1: TreeNode?, _ t2: TreeNode?) -> Bool {
if t2 == nil {
return true
}
if t1 == nil {
return false
}
if isSameTree(t1, t2) {
return true
}
return checkSubTree(t1!.left, t2) || checkSubTree(t1!.right, t2)
}
private func isSameTree(_ t1: TreeNode?, _ t2: TreeNode?) -> Bool {
if t1 == nil && t2 == nil {
return true
}
if t1 == nil || t2 == nil {
return false
}
if t1!.val != t2!.val {
return false
}
return isSameTree(t1!.left, t2!.left) && isSameTree(t1!.right, t2!.right)
}
}