forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathradiantchoi.swift
More file actions
40 lines (37 loc) ยท 1.5 KB
/
radiantchoi.swift
File metadata and controls
40 lines (37 loc) ยท 1.5 KB
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
// Definition for a binary tree node.
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 {
// ์ข
๋ฃ์กฐ๊ฑด์ ์ค์ ํ๊ณ ์ฌ๊ท๋ก ๋๋ ค์ ํธ๋ฆฌ ์ ์ฒด๋ฅผ ์ ๊ฒ - DFS
func isSameTree(_ p: TreeNode?, _ q: TreeNode?) -> Bool {
// ๋ ๋ค nil์ด๋ฉด ๊ฐ์ ๊ฒ์ผ๋ก ์ทจ๊ธ - TreeNode๋ Equatable์ ์ฑํํ์ง ์์์, p == q์ ๊ฐ์ ์ง์ ๋น๊ต๋ ๋ถ๊ฐ๋ฅ
if p == nil && q == nil { return true }
// ๋ ๋ค nil์ธ ๊ฒฝ์ฐ๊ฐ ์๋๋ผ๋ฉด, ํ ์ชฝ์ด๋ผ๋ nil์ด๋ฉด ๊ฐ์ ๊ฒ์ด ์๋๋ฏ๋ก false
guard let p, let q else { return false }
// ๊ฐ์ด ๊ฐ์ง ์์ผ๋ฉด false
guard p.val == q.val else { return false }
// ๋ ๋ค nil์ด ์๋๊ณ , ๊ฐ์ด ๊ฐ์๊น์ง ๊ฒ์ฆํ ์ํ
if p.isLeafNode && q.isLeafNode {
// ์์์ด ์๋ค๋ฉด true ๋ฐํ
return true
} else {
// ์์์ด ์๋ค๋ฉด ์์๋ค์ ๋ํด ๊ฐ๊ฐ ๊ฒ์ฌ ์ํ
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
}
}
}
extension TreeNode {
var isLeafNode: Bool {
left == nil && right == nil
}
}