forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdelight010.swift
More file actions
37 lines (31 loc) · 984 Bytes
/
delight010.swift
File metadata and controls
37 lines (31 loc) · 984 Bytes
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
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init() { self.val = 0; self.left = nil; self.right = nil; }
public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
self.val = val
self.left = left
self.right = right
}
}
class Solution {
// Time O(n)
// Space best O(log n)
// Space worst O(n)
func isSameTree(_ p: TreeNode?, _ q: TreeNode?) -> Bool {
return dfs(p, q)
}
private func dfs(_ p: TreeNode?, _ q: TreeNode?) -> Bool {
if p == nil && q == nil {
return true
}
guard let p = p else { return false }
guard let q = q else { return false }
if p.val != q.val {
return false
}
return dfs(p.left, q.left) && dfs(p.right, q.right)
}
}