mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Merge pull request #104 from Joshua-Lu/patch-21
添加 0617.合并二叉树 Java版本 递归与迭代
This commit is contained in:
@ -256,8 +256,10 @@ public:
|
||||
|
||||
|
||||
Java:
|
||||
```java
|
||||
|
||||
```Java
|
||||
class Solution {
|
||||
// 递归
|
||||
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
|
||||
if (root1 == null) return root2;
|
||||
if (root2 == null) return root1;
|
||||
@ -270,6 +272,45 @@ class Solution {
|
||||
}
|
||||
```
|
||||
|
||||
```Java
|
||||
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:
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user