-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryTreePruning.kt
100 lines (72 loc) · 2.05 KB
/
BinaryTreePruning.kt
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package problems
import problems.datastructure.*
class BinaryTreePruning {
fun pruneTree(root: TreeNode?): TreeNode? {
if (root == null) return null
root.left = pruneTree(root.left)
root.right = pruneTree(root.right)
if (root.`val` == 0 && root.left == null && root.right == null) {
return null
}
return root
}
fun pruneTreeMySolution(root: TreeNode?): TreeNode? {
nodys(root)
if (root?.`val` == -99) {
return null
} else {
return root
}
}
private fun nodys(node: TreeNode?) {
node?.left?.let { nodys(it) }
node?.right?.let { nodys(it) }
if (node?.left?.`val` == -99) {
node.left = null
}
if (node?.right?.`val` == -99) {
node.right = null
}
if (node?.`val` == 0 && node.left == null && node.right == null) {
node.`val` = -99
}
}
//region tc
fun tc1() {
val root = TreeNode(1)
root.right = TreeNode(1)
root.right?.left = TreeNode(0)
root.right?.right = TreeNode(1)
root.right?.left?.left = TreeNode(0)
root.right?.left?.right = TreeNode(0)
root.right?.left?.left?.left = TreeNode(1)
root.levelOrderPrint()
println()
pruneTree(root).levelOrderPrint()
println()
}
fun tc2() {
val root = TreeNode(1)
root.left = TreeNode(0)
root.left?.left = TreeNode(0)
root.left?.right = TreeNode(0)
root.right = TreeNode(1)
root.right?.left = TreeNode(0)
root.right?.right = TreeNode(1)
root.postOrderPrint()
println()
pruneTree(root).levelOrderPrint()
println()
}
fun tc3() {
val root = TreeNode(1)
root.right = TreeNode(2)
root.right?.left = TreeNode(3)
root.right?.right = TreeNode(4)
root.postOrderPrint()
println()
pruneTree(root).levelOrderPrint()
println()
}
//endregion
}