Skip to content

Commit

Permalink
添加0617.合并二叉树.md队列迭代Java解法
Browse files Browse the repository at this point in the history
  • Loading branch information
ironartisan committed Sep 6, 2021
1 parent 2cb7609 commit 2c584ce
Showing 1 changed file with 38 additions and 1 deletion.
39 changes: 38 additions & 1 deletion problems/0617.合并二叉树.md
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ class Solution {

```Java
class Solution {
// 迭代
// 使用栈迭代
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if (root1 == null) {
return root2;
Expand Down Expand Up @@ -310,6 +310,43 @@ class Solution {
}
}
```
```java
class Solution {
// 使用队列迭代
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if (root1 == null) return root2;
if (root2 ==null) return root1;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root1);
queue.offer(root2);
while (!queue.isEmpty()) {
TreeNode node1 = queue.poll();
TreeNode node2 = queue.poll();
// 此时两个节点一定不为空,val相加
node1.val = node1.val + node2.val;
// 如果两棵树左节点都不为空,加入队列
if (node1.left != null && node2.left != null) {
queue.offer(node1.left);
queue.offer(node2.left);
}
// 如果两棵树右节点都不为空,加入队列
if (node1.right != null && node2.right != null) {
queue.offer(node1.right);
queue.offer(node2.right);
}
// 若node1的左节点为空,直接赋值
if (node1.left == null && node2.left != null) {
node1.left = node2.left;
}
// 若node2的左节点为空,直接赋值
if (node1.right == null && node2.right != null) {
node1.right = node2.right;
}
}
return root1;
}
}
```

## Python

Expand Down

0 comments on commit 2c584ce

Please sign in to comment.