Skip to content

Commit 20401ca

Browse files
Merge pull request #219
add new problem 23.09
2 parents 25ed040 + 5f2d89c commit 20401ca

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

contest/src/main/java/com/github/contest/binaryTree/BinaryTreeAlternativeSolution.kt

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,26 @@ class FindElementsAlternativeSolution(root: TreeNode?) {
2828
fun find(target: Int): Boolean {
2929
return values.contains(target)
3030
}
31+
}
32+
33+
/**
34+
* 572. Subtree of Another Tree
35+
* Alternative Solution
36+
* Serialization
37+
*/
38+
39+
fun isSubtreeSerialization(root: TreeNode?, subRoot: TreeNode?): Boolean {
40+
41+
val stringRoot = serialize(root)
42+
val stringSubRoot = serialize(subRoot)
43+
44+
return stringRoot.contains(stringSubRoot)
45+
}
46+
47+
48+
fun serialize(root: TreeNode?): String {
49+
if (root == null) return "null"
50+
51+
// Use preorder traversal with markers
52+
return "#${root.`val`} ${serialize(root.left)} ${serialize(root.right)}"
3153
}

contest/src/main/java/com/github/contest/binaryTree/BinaryTreeLeetcode.kt

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,3 +260,48 @@ fun mergeTrees(root1: TreeNode?, root2: TreeNode?): TreeNode? {
260260

261261
return newRoot
262262
}
263+
264+
/**
265+
* 572. Subtree of Another Tree
266+
*/
267+
268+
fun isSubtree(root: TreeNode?, subRoot: TreeNode?): Boolean {
269+
270+
val queue = LinkedList<TreeNode>().apply {
271+
offer(root)
272+
}
273+
274+
while (queue.isNotEmpty()) {
275+
val size = queue.size
276+
277+
for (i in 0 until size) {
278+
val node = queue.poll()
279+
val nodeVal = node?.`val` ?: 0
280+
val subRootVal = subRoot?.`val` ?: 0
281+
282+
if (nodeVal == subRootVal) {
283+
if (isSameTree(node, subRoot)) return true
284+
}
285+
286+
node?.left?.let {
287+
queue.offer(it)
288+
}
289+
290+
node?.right?.let {
291+
queue.offer(it)
292+
}
293+
}
294+
}
295+
296+
return false
297+
298+
}
299+
300+
private fun isSameTree(root: TreeNode?, subRoot: TreeNode?): Boolean {
301+
if (root == null && subRoot == null) return true
302+
if (root?.`val` != subRoot?.`val`) return false
303+
root ?: return false
304+
subRoot ?: return false
305+
306+
return isSameTree(root?.left, subRoot?.left) && isSameTree(root?.right, subRoot?.right)
307+
}

0 commit comments

Comments
 (0)