forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0572-subtree-of-another-tree.scala
33 lines (32 loc) · 1.04 KB
/
0572-subtree-of-another-tree.scala
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
/**
* Definition for a binary tree node.
* class TreeNode(_value: Int = 0, _left: TreeNode = null, _right: TreeNode = null) {
* var value: Int = _value
* var left: TreeNode = _left
* var right: TreeNode = _right
* }
*/
object Solution {
def isSubtree(root: TreeNode, subRoot: TreeNode): Boolean = {
if (root == null && subRoot == null) {
return true
} else if (root != null && subRoot == null) {
return true
} else if (root == null && subRoot != null) {
return false
} else {
return isSameTree(root, subRoot) || (isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot))
}
}
def isSameTree(p: TreeNode, q: TreeNode): Boolean = {
if (p == null && q == null) {
return true
} else if (p == null || q == null) {
return false
} else if (p.value != q.value) {
return false
} else {
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
}
}
}