Skip to content

Commit 4d3ddd2

Browse files
author
Thuy Trinh
committed
Solution for "Flatten Binary Tree to Linked List"
1 parent 610eaae commit 4d3ddd2

File tree

4 files changed

+75
-1
lines changed

4 files changed

+75
-1
lines changed

build.gradle

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
buildscript {
2-
ext.kotlinVersion = '1.2.0'
2+
ext.kotlinVersion = '1.2.10'
33

44
repositories {
55
mavenCentral()

src/main/java/leetcode/binarytreeboundary/TreeNode.java

+4
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
package leetcode.binarytreeboundary;
22

3+
import org.jetbrains.annotations.Nullable;
4+
35
public class TreeNode {
46
public int val;
7+
@Nullable
58
public TreeNode left;
9+
@Nullable
610
public TreeNode right;
711

812
public TreeNode(int x) {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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 numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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+
}

0 commit comments

Comments
 (0)