forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.ts
41 lines (40 loc) · 1.31 KB
/
Solution.ts
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
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function getAllElements(root1: TreeNode | null, root2: TreeNode | null): number[] {
const res = [];
const stacks = [[], []];
while (root1 != null || stacks[0].length !== 0 || root2 != null || stacks[1].length !== 0) {
if (root1 != null) {
stacks[0].push(root1);
root1 = root1.left;
} else if (root2 != null) {
stacks[1].push(root2);
root2 = root2.left;
} else {
if (
(stacks[0][stacks[0].length - 1] ?? { val: Infinity }).val <
(stacks[1][stacks[1].length - 1] ?? { val: Infinity }).val
) {
const { val, right } = stacks[0].pop();
res.push(val);
root1 = right;
} else {
const { val, right } = stacks[1].pop();
res.push(val);
root2 = right;
}
}
}
return res;
}