-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path1305.All-Elements-in-Two-Binary-Search-Trees.java
67 lines (58 loc) · 1.82 KB
/
1305.All-Elements-in-Two-Binary-Search-Trees.java
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// https://leetcode.com/problems/all-elements-in-two-binary-search-trees/
// algorithms
// Easy (76.89%)
// Total Accepted: 6,458
// Total Submissions: 8,399
// beats 100.0% of java submissions
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
/**
* Definition for a binary tree node. public class TreeNode { int val; TreeNode
* left; TreeNode right; TreeNode(int x) { val = x; } }
*/
class Solution {
public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
ArrayList<Integer> res = new ArrayList<>();
LinkedList<TreeNode> stack1 = new LinkedList<>();
LinkedList<TreeNode> stack2 = new LinkedList<>();
while (root1 != null || root2 != null) {
if (root1 != null) {
stack1.addFirst(root1);
root1 = root1.left;
}
if (root2 != null) {
stack2.addFirst(root2);
root2 = root2.left;
}
}
while (!stack1.isEmpty() || !stack2.isEmpty()) {
TreeNode tmp1 = stack1.peekFirst();
TreeNode tmp2 = stack2.peekFirst();
LinkedList<TreeNode> tmpStack = null;
if (tmp1 == null) {
tmpStack = stack2;
} else if (tmp2 == null) {
tmpStack = stack1;
} else {
tmpStack = tmp1.val >= tmp2.val ? stack2 : stack1;
}
TreeNode tmp = tmpStack.pollFirst();
res.add(tmp.val);
if (tmp.right != null) {
tmp = tmp.right;
while (tmp != null) {
tmpStack.addFirst(tmp);
tmp = tmp.left;
}
}
}
return res;
}
}