Skip to content

Commit 5eafc82

Browse files
[N-0] refactor 114
1 parent 0deee44 commit 5eafc82

File tree

2 files changed

+43
-23
lines changed

2 files changed

+43
-23
lines changed

Diff for: src/main/java/com/fishercoder/solutions/_114.java

+15-23
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import com.fishercoder.common.classes.TreeNode;
44

55
/**
6+
* 114. Flatten Binary Tree to Linked List
7+
*
68
* Given a binary tree, flatten it to a linked list in-place.
79
810
For example,
@@ -31,31 +33,21 @@
3133
*/
3234
public class _114 {
3335

34-
public void flatten(TreeNode root) {
35-
while (root != null) {
36-
if (root.left != null) {
37-
TreeNode previousNode = root.left;
38-
while (previousNode.right != null) {
39-
previousNode = previousNode.right;
36+
public static class Solution1 {
37+
public void flatten(TreeNode root) {
38+
while (root != null) {
39+
if (root.left != null) {
40+
TreeNode previousNode = root.left;
41+
while (previousNode.right != null) {
42+
previousNode = previousNode.right;
43+
}
44+
previousNode.right = root.right;
45+
root.right = root.left;
46+
root.left = null;
4047
}
41-
previousNode.right = root.right;
42-
root.right = root.left;
43-
root.left = null;
48+
root = root.right;
4449
}
45-
root = root.right;
4650
}
4751
}
4852

49-
public static void main(String... args) {
50-
TreeNode root = new TreeNode(1);
51-
root.left = new TreeNode(2);
52-
root.left.left = new TreeNode(3);
53-
root.left.right = new TreeNode(4);
54-
root.right = new TreeNode(5);
55-
root.right.right = new TreeNode(6);
56-
57-
_114 test = new _114();
58-
test.flatten(root);
59-
}
60-
61-
}
53+
}

Diff for: src/test/java/com/fishercoder/_114Test.java

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.fishercoder;
2+
3+
import com.fishercoder.common.classes.TreeNode;
4+
import com.fishercoder.common.utils.TreeUtils;
5+
import com.fishercoder.solutions._114;
6+
import org.junit.BeforeClass;
7+
import org.junit.Test;
8+
9+
import java.util.Arrays;
10+
11+
public class _114Test {
12+
private static _114.Solution1 solution1;
13+
private static TreeNode root;
14+
15+
@BeforeClass
16+
public static void setup() {
17+
solution1 = new _114.Solution1();
18+
}
19+
20+
@Test
21+
public void test1() {
22+
root = TreeUtils.constructBinaryTree(Arrays.asList(1, 2, 5, 3, 4, null, 6));
23+
TreeUtils.printBinaryTree(root);
24+
solution1.flatten(root);
25+
TreeUtils.printBinaryTree(root);
26+
}
27+
28+
}

0 commit comments

Comments
 (0)