Skip to content

Commit 2c584ce

Browse files
committed
添加0617.合并二叉树.md队列迭代Java解法
1 parent 2cb7609 commit 2c584ce

File tree

1 file changed

+38
-1
lines changed

1 file changed

+38
-1
lines changed

problems/0617.合并二叉树.md

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -274,7 +274,7 @@ class Solution {
274274

275275
```Java
276276
class Solution {
277-
// 迭代
277+
// 使用栈迭代
278278
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
279279
if (root1 == null) {
280280
return root2;
@@ -310,6 +310,43 @@ class Solution {
310310
}
311311
}
312312
```
313+
```java
314+
class Solution {
315+
// 使用队列迭代
316+
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
317+
if (root1 == null) return root2;
318+
if (root2 ==null) return root1;
319+
Queue<TreeNode> queue = new LinkedList<>();
320+
queue.offer(root1);
321+
queue.offer(root2);
322+
while (!queue.isEmpty()) {
323+
TreeNode node1 = queue.poll();
324+
TreeNode node2 = queue.poll();
325+
// 此时两个节点一定不为空,val相加
326+
node1.val = node1.val + node2.val;
327+
// 如果两棵树左节点都不为空,加入队列
328+
if (node1.left != null && node2.left != null) {
329+
queue.offer(node1.left);
330+
queue.offer(node2.left);
331+
}
332+
// 如果两棵树右节点都不为空,加入队列
333+
if (node1.right != null && node2.right != null) {
334+
queue.offer(node1.right);
335+
queue.offer(node2.right);
336+
}
337+
// 若node1的左节点为空,直接赋值
338+
if (node1.left == null && node2.left != null) {
339+
node1.left = node2.left;
340+
}
341+
// 若node2的左节点为空,直接赋值
342+
if (node1.right == null && node2.right != null) {
343+
node1.right = node2.right;
344+
}
345+
}
346+
return root1;
347+
}
348+
}
349+
```
313350

314351
## Python
315352

0 commit comments

Comments
 (0)