Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commite787afd

Browse files
add a solution for 617
1 parentf6931f5 commite787afd

File tree

2 files changed

+32
-8
lines changed

2 files changed

+32
-8
lines changed

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

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,35 @@
55
publicclass_617 {
66

77
publicstaticclassSolution1 {
8-
publicTreeNodemergeTrees(TreeNodet1,TreeNodet2) {
9-
if (t1 ==null) {
10-
returnt2;
8+
publicTreeNodemergeTrees(TreeNoderoot1,TreeNoderoot2) {
9+
if (root1 ==null) {
10+
returnroot2;
1111
}
12-
if (t2 ==null) {
13-
returnt1;
12+
if (root2 ==null) {
13+
returnroot1;
1414
}
15-
TreeNodemergedNode =newTreeNode(t1.val +t2.val);
16-
mergedNode.left =mergeTrees(t1.left,t2.left);
17-
mergedNode.right =mergeTrees(t1.right,t2.right);
15+
TreeNodemergedNode =newTreeNode(root1.val +root2.val);
16+
mergedNode.left =mergeTrees(root1.left,root2.left);
17+
mergedNode.right =mergeTrees(root1.right,root2.right);
1818
returnmergedNode;
1919
}
2020
}
2121

22+
publicstaticclassSolution2 {
23+
/**
24+
* My completely original solution on 9/20/2021, no new extra nodes created.
25+
*/
26+
publicTreeNodemergeTrees(TreeNoderoot1,TreeNoderoot2) {
27+
if (root1 ==null) {
28+
returnroot2;
29+
}elseif (root2 ==null) {
30+
returnroot1;
31+
}
32+
root1.val +=root2.val;
33+
root1.left =mergeTrees(root1.left,root2.left);
34+
root1.right =mergeTrees(root1.right,root2.right);
35+
returnroot1;
36+
}
37+
}
38+
2239
}

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,22 @@
1111

1212
publicclass_617Test {
1313
privatestatic_617.Solution1solution1;
14+
privatestatic_617.Solution2solution2;
1415

1516
@BeforeClass
1617
publicstaticvoidsetup() {
1718
solution1 =new_617.Solution1();
19+
solution2 =new_617.Solution2();
1820
}
1921

2022
@Test
2123
publicvoidtest1() {
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+
publicvoidtest2() {
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)

[8]ページ先頭

©2009-2025 Movatter.jp