Skip to content

Commit 5f2d89c

Browse files
add 572 alt sol with serialization
1 parent 33d8f71 commit 5f2d89c

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-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
}

0 commit comments

Comments
 (0)