Skip to content

Commit e787afd

Browse files
add a solution for 617
1 parent f6931f5 commit e787afd

File tree

2 files changed

+32
-8
lines changed

2 files changed

+32
-8
lines changed

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

+25-8
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,35 @@
55
public class _617 {
66

77
public static class Solution1 {
8-
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
9-
if (t1 == null) {
10-
return t2;
8+
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
9+
if (root1 == null) {
10+
return root2;
1111
}
12-
if (t2 == null) {
13-
return t1;
12+
if (root2 == null) {
13+
return root1;
1414
}
15-
TreeNode mergedNode = new TreeNode(t1.val + t2.val);
16-
mergedNode.left = mergeTrees(t1.left, t2.left);
17-
mergedNode.right = mergeTrees(t1.right, t2.right);
15+
TreeNode mergedNode = new TreeNode(root1.val + root2.val);
16+
mergedNode.left = mergeTrees(root1.left, root2.left);
17+
mergedNode.right = mergeTrees(root1.right, root2.right);
1818
return mergedNode;
1919
}
2020
}
2121

22+
public static class Solution2 {
23+
/**
24+
* My completely original solution on 9/20/2021, no new extra nodes created.
25+
*/
26+
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
27+
if (root1 == null) {
28+
return root2;
29+
} else if (root2 == null) {
30+
return root1;
31+
}
32+
root1.val += root2.val;
33+
root1.left = mergeTrees(root1.left, root2.left);
34+
root1.right = mergeTrees(root1.right, root2.right);
35+
return root1;
36+
}
37+
}
38+
2239
}

src/test/java/com/fishercoder/_617Test.java

+7
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,22 @@
1111

1212
public class _617Test {
1313
private static _617.Solution1 solution1;
14+
private static _617.Solution2 solution2;
1415

1516
@BeforeClass
1617
public static void setup() {
1718
solution1 = new _617.Solution1();
19+
solution2 = new _617.Solution2();
1820
}
1921

2022
@Test
2123
public void test1() {
2224
assertEquals(TreeUtils.constructBinaryTree(Arrays.asList(3, 4, 5, 5, 4, null, 7)), solution1.mergeTrees(TreeUtils.constructBinaryTree(Arrays.asList(1, 3, 2, 5)), TreeUtils.constructBinaryTree(Arrays.asList(2, 1, 3, null, 4, null, 7))));
2325
}
2426

27+
@Test
28+
public void test2() {
29+
assertEquals(TreeUtils.constructBinaryTree(Arrays.asList(3, 4, 5, 5, 4, null, 7)), solution2.mergeTrees(TreeUtils.constructBinaryTree(Arrays.asList(1, 3, 2, 5)), TreeUtils.constructBinaryTree(Arrays.asList(2, 1, 3, null, 4, null, 7))));
30+
}
31+
2532
}

0 commit comments

Comments
 (0)