-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTree617.java
More file actions
30 lines (25 loc) · 785 Bytes
/
Copy pathTree617.java
File metadata and controls
30 lines (25 loc) · 785 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if (root1 == null && root2 == null) return null;
TreeNode root = new TreeNode();
dfs(root, root1);
dfs(root, root2);
return root;
}
private void dfs(TreeNode root, TreeNode target) {
if (target == null) return;
else root.val += target.val;
if (target.left != null) {
if (root.left == null) {
root.left = new TreeNode();
}
dfs(root.left, target.left);
}
if (target.right != null) {
if (root.right == null) {
root.right = new TreeNode();
}
dfs(root.right, target.right);
}
}
}