-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ617MergeBinaryTrees.java
More file actions
39 lines (35 loc) · 1.04 KB
/
Q617MergeBinaryTrees.java
File metadata and controls
39 lines (35 loc) · 1.04 KB
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
31
32
33
34
35
36
37
38
39
/*
@b-knd (jingru) on 06 August 2022 10:47:00
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
TreeNode head;
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
//one of the trees is empty (no more nodes
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;
}
}
//Runtime: 1 ms, faster than 81.09% of Java online submissions for Merge Two Binary Trees.
//Memory Usage: 50.3 MB, less than 80.43% of Java online submissions for Merge Two Binary Trees.