-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.scala
executable file
·47 lines (37 loc) · 1.01 KB
/
Solution.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package RemoveLeafNodes
class TreeNode(_value: Int = 0, _left: TreeNode = null, _right: TreeNode = null) {
var value: Int = _value
var left: TreeNode = _left
var right: TreeNode = _right
}
// https://leetcode.com/problems/delete-leaves-with-a-given-value/
object Solution {
def removeLeafNodes(root: TreeNode, target: Int): TreeNode = {
def isLeaf(root: TreeNode): Boolean =
root.left == null && root.right == null
def removeOnce(root: TreeNode): TreeNode = {
if (root == null) null
else if (isLeaf(root) && root.value == target) null
else
new TreeNode(
root.value,
removeOnce(root.left),
removeOnce(root.right)
)
}
def containsLeaves(root: TreeNode): Boolean = {
if (root == null) false
else if (isLeaf(root) && root.value == target) true
else
containsLeaves(root.left) ||
containsLeaves(root.right)
}
if (containsLeaves(root)) {
removeLeafNodes(
removeOnce(root),
target
)
}
else root
}
}