Skip to content

Commit b5735e5

Browse files
[N-0] refactor 156
1 parent f0278a8 commit b5735e5

File tree

2 files changed

+45
-9
lines changed

2 files changed

+45
-9
lines changed

src/main/java/com/fishercoder/solutions/_156.java

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import com.fishercoder.common.classes.TreeNode;
44

55
/**
6+
* 156. Binary Tree Upside Down
7+
*
68
* Given a binary tree where all the right nodes are either leaf nodes with a sibling
79
* (a left node that shares the same parent node) or empty,
810
* flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root.
@@ -14,25 +16,29 @@
1416
2 3
1517
/ \
1618
4 5
19+
1720
return the root of the binary tree [4,5,2,#,#,3,1].
1821
4
1922
/ \
2023
5 2
2124
/ \
2225
3 1
26+
2327
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
2428
*/
2529
public class _156 {
2630

27-
public TreeNode upsideDownBinaryTree(TreeNode root) {
28-
if (root == null || root.left == null && root.right == null) {
29-
return root;
31+
public static class Solution1 {
32+
public TreeNode upsideDownBinaryTree(TreeNode root) {
33+
if (root == null || root.left == null && root.right == null) {
34+
return root;
35+
}
36+
TreeNode newRoot = upsideDownBinaryTree(root.left);
37+
root.left.left = root.right;
38+
root.left.right = root;
39+
root.left = null;
40+
root.right = null;
41+
return newRoot;
3042
}
31-
TreeNode newRoot = upsideDownBinaryTree(root.left);
32-
root.left.left = root.right;
33-
root.left.right = root;
34-
root.left = null;
35-
root.right = null;
36-
return newRoot;
3743
}
3844
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.fishercoder;
2+
3+
import com.fishercoder.common.classes.TreeNode;
4+
import com.fishercoder.common.utils.TreeUtils;
5+
import com.fishercoder.solutions._156;
6+
import org.junit.BeforeClass;
7+
import org.junit.Test;
8+
9+
import java.util.Arrays;
10+
11+
import static org.junit.Assert.assertEquals;
12+
13+
public class _156Test {
14+
private static _156.Solution1 solution1;
15+
private static TreeNode root;
16+
private static TreeNode expected;
17+
18+
@BeforeClass
19+
public static void setup() {
20+
solution1 = new _156.Solution1();
21+
}
22+
23+
@Test
24+
public void test1() {
25+
root = TreeUtils.constructBinaryTree(Arrays.asList(1, 2, 3, 4, 5));
26+
expected = TreeUtils.constructBinaryTree(Arrays.asList(4, 5, 2, null, null, 3, 1));
27+
assertEquals(expected, solution1.upsideDownBinaryTree(root));
28+
}
29+
30+
}

0 commit comments

Comments
 (0)