Skip to content

Commit

Permalink
Update 0617.合并二叉树.md
Browse files Browse the repository at this point in the history
添加 0617.合并二叉树 Java版本
  • Loading branch information
Joshua-Lu authored May 13, 2021
1 parent 1f5408b commit 1dd57ca
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions problems/0617.合并二叉树.md
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,60 @@ public:
Java:
```Java
class Solution {
// 递归
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if (root1 == null) {
return root2;
}
if (root2 == null) {
return root1;
}
root1.val += root2.val;
root1.left = mergeTrees(root1.left, root2.left);
root1.right = mergeTrees(root1.right, root2.right);
return root1;
}
}
class Solution {
// 迭代
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if (root1 == null) {
return root2;
}
if (root2 == null) {
return root1;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root2);
stack.push(root1);
while (!stack.isEmpty()) {
TreeNode node1 = stack.pop();
TreeNode node2 = stack.pop();
node1.val += node2.val;
if (node2.right != null && node1.right != null) {
stack.push(node2.right);
stack.push(node1.right);
} else {
if (node1.right == null) {
node1.right = node2.right;
}
}
if (node2.left != null && node1.left != null) {
stack.push(node2.left);
stack.push(node1.left);
} else {
if (node1.left == null) {
node1.left = node2.left;
}
}
}
return root1;
}
}
```

Python:

Expand Down

0 comments on commit 1dd57ca

Please sign in to comment.