๐ Problem
๐ BFS approach
Create two queue with bread-first search to all nodes.
To handle null case, if null, don't add left & right nodes to queue
BFS Code (Kotlin)
import java.util.LinkedList
import java.util.Queue
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
class SameTree {
fun isSameTree(p: TreeNode?, q: TreeNode?): Boolean {
// 1. queue 2๊ฐ ์ด๊ธฐํ ๋ฐ ๋ฃจํธ ๋
ธ๋ ์ฝ์
val pQueue1 : Queue<TreeNode?> = LinkedList<TreeNode?>()
val qQueue2 : Queue<TreeNode?> = LinkedList<TreeNode?>()
pQueue1.add(p)
qQueue2.add(q)
// 2. queue ๊ฐ ๋๋ค ๋น์ด์์ง ์์ ๋ ๊น์ง
// (๋น์ด์์ ์๊ฐ ์๋๊ฒ ์ด์ฐจํผ NULL ๊ฐ ๊ฐ์ ธ๋ ํ์๋ ์์)
while (pQueue1.isNotEmpty() && qQueue2.isNotEmpty()) {
val pNode = pQueue1.poll()
val qNode = qQueue2.poll()
// 3. ํ์ฌ ๋
ธ๋ ๊ฐ ๋น๊ต => ๋ค๋ฅด๋ฉด return false
// Node ๊ฐ null ์ธ์ง ์ฌ๋ถ๋ฅผ ๊ฒ์ฌํด์ผํจ
// ? operator if null -> null return
if (pNode?.`val` != qNode?.`val`) return false
// 4. ํ์ฌ ๋
ธ๋๊ฐ NULL ์ด ์๋ ๊ฒฝ์ฐ
// ์ผ์ชฝ ์ค๋ฅธ์ชฝ ๋
ธ๋๋ฅผ ๊ฐ๊ฐ์ queue ์ push
if (pNode != null) {
pQueue1.add(pNode.left)
pQueue1.add(pNode.right)
}
if (qNode != null) {
qQueue2.add(qNode.left)
qQueue2.add(qNode.right)
}
}
return true
}
}
๐ Recursion approach
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
class SameTree {
fun isSameTreeRecursion(p: TreeNode?, q: TreeNode?): Boolean {
// ๋๋ค null => leaf node ๋ฅผ ์ง๋ ๋์๋ฝ์ผ๋ก ๋๋ฌ => ์ฌ๊ท ์ข
๋ฃ ์กฐ๊ฑด
if (p == null && q == null) return true
if (p?.`val` != q?.`val`) return false
// preorder traversal
return isSameTreeRecursion(p?.left, q?.left) && isSameTreeRecursion(p?.right, q?.right)
}
}
'Algorithm > Algorithm (๋ฌธ์ ํ์ด)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค] 2217 ๋กํ (0) | 2022.09.28 |
---|---|
[๋ฐฑ์ค] 11779 ์ต์๋น์ฉ ๊ตฌํ๊ธฐ 2 (0) | 2022.09.23 |
[๋ฐฑ์ค 1158] ์์ธํธ์ค ๋ฌธ์ (2) | 2021.03.06 |
[Geeks for Geeks] Insert a node in a BST (0) | 2021.02.23 |
[๋ฐฑ์ค 11651] ์ขํ ์ ๋ ฌํ๊ธฐ 2 (0) | 2021.02.21 |