File tree 4 files changed +75
-1
lines changed
test/java/leetcode/flattenbtree
4 files changed +75
-1
lines changed Original file line number Diff line number Diff line change 1
1
buildscript {
2
- ext. kotlinVersion = ' 1.2.0 '
2
+ ext. kotlinVersion = ' 1.2.10 '
3
3
4
4
repositories {
5
5
mavenCentral()
Original file line number Diff line number Diff line change 1
1
package leetcode .binarytreeboundary ;
2
2
3
+ import org .jetbrains .annotations .Nullable ;
4
+
3
5
public class TreeNode {
4
6
public int val ;
7
+ @ Nullable
5
8
public TreeNode left ;
9
+ @ Nullable
6
10
public TreeNode right ;
7
11
8
12
public TreeNode (int x ) {
Original file line number Diff line number Diff line change
1
+ package leetcode.flattenbtree
2
+
3
+ import leetcode.binarytreeboundary.TreeNode
4
+
5
+ /* *
6
+ * https://leetcode.com/problems/flatten-binary-tree-to-linked-list/description/
7
+ */
8
+ class Solution {
9
+ fun flatten (root : TreeNode ? ) {
10
+ root?.flatten()
11
+ }
12
+
13
+ private fun TreeNode.flatten (): TreeNode ? {
14
+ if (left == null && right == null ) {
15
+ return this
16
+ }
17
+
18
+ val newLeftLeaf = left?.flatten()
19
+ val newRightLeaf = right?.flatten()
20
+ val oldRight = right
21
+ right = left ? : oldRight
22
+ left = null
23
+ newLeftLeaf?.right = oldRight
24
+ return newRightLeaf ? : newLeftLeaf ? : this
25
+ }
26
+ }
Original file line number Diff line number Diff line change
1
+ package leetcode.flattenbtree
2
+
3
+ import leetcode.binarytreeboundary.isEqualTo
4
+ import leetcode.binarytreeboundary.node
5
+ import org.amshove.kluent.shouldBeTrue
6
+ import org.junit.Test
7
+
8
+ class SolutionTest {
9
+ @Test
10
+ fun case0 () {
11
+ val root = node(1 ) {
12
+ left = node(2 ) {
13
+ left = node(3 )
14
+ right = node(4 )
15
+ }
16
+ right = node(5 ) {
17
+ right = node(6 )
18
+ }
19
+ }
20
+ Solution ().flatten(root)
21
+ root.isEqualTo(node(1 ) {
22
+ right = node(2 ) {
23
+ right = node(3 ) {
24
+ right = node(4 ) {
25
+ right = node(5 ) {
26
+ right = node(6 )
27
+ }
28
+ }
29
+ }
30
+ }
31
+ }).shouldBeTrue()
32
+ }
33
+
34
+ @Test
35
+ fun case1 () {
36
+ val root = node(1 ) {
37
+ left = node(2 )
38
+ }
39
+ Solution ().flatten(root)
40
+ root.isEqualTo(node(1 ) {
41
+ right = node(2 )
42
+ }).shouldBeTrue()
43
+ }
44
+ }
You can’t perform that action at this time.
0 commit comments