Skip to content

Commit 1dd57ca

Browse files
authored
Update 0617.合并二叉树.md
添加 0617.合并二叉树 Java版本
1 parent 1f5408b commit 1dd57ca

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

problems/0617.合并二叉树.md

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,60 @@ public:
256256
257257
258258
Java:
259+
```Java
260+
class Solution {
261+
// 递归
262+
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
263+
if (root1 == null) {
264+
return root2;
265+
}
266+
if (root2 == null) {
267+
return root1;
268+
}
269+
root1.val += root2.val;
270+
root1.left = mergeTrees(root1.left, root2.left);
271+
root1.right = mergeTrees(root1.right, root2.right);
272+
return root1;
273+
}
274+
}
259275
276+
class Solution {
277+
// 迭代
278+
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
279+
if (root1 == null) {
280+
return root2;
281+
}
282+
if (root2 == null) {
283+
return root1;
284+
}
285+
Stack<TreeNode> stack = new Stack<>();
286+
stack.push(root2);
287+
stack.push(root1);
288+
while (!stack.isEmpty()) {
289+
TreeNode node1 = stack.pop();
290+
TreeNode node2 = stack.pop();
291+
node1.val += node2.val;
292+
if (node2.right != null && node1.right != null) {
293+
stack.push(node2.right);
294+
stack.push(node1.right);
295+
} else {
296+
if (node1.right == null) {
297+
node1.right = node2.right;
298+
}
299+
}
300+
if (node2.left != null && node1.left != null) {
301+
stack.push(node2.left);
302+
stack.push(node1.left);
303+
} else {
304+
if (node1.left == null) {
305+
node1.left = node2.left;
306+
}
307+
}
308+
}
309+
return root1;
310+
}
311+
}
312+
```
260313

261314
Python:
262315

0 commit comments

Comments
 (0)