File tree 1 file changed +31
-30
lines changed
scripts/algorithms/A/All Elements in Two Binary Search Trees
1 file changed +31
-30
lines changed Original file line number Diff line number Diff line change 1
- class Solution {
2
- public List <Integer > getAllElements (TreeNode root1 , TreeNode root2 ) {
3
- List <Integer > mylist = new ArrayList <>();
4
-
5
- there (root1 , mylist );
6
- there (root2 , mylist );
7
-
8
- int [] arr = new int [mylist .size ()];
9
- for (int i =0 ; i <arr .length ; i ++){
10
- arr [i ]=mylist .get (i );
1
+ // Runtime: 19 ms (Top 53.0%) | Memory: 44.86 MB (Top 93.0%)
2
+
3
+ class Solution {
4
+ public List <Integer > getAllElements (TreeNode root1 , TreeNode root2 ) {
5
+ Stack <TreeNode > st1 = new Stack <>();
6
+ Stack <TreeNode > st2 = new Stack <>();
7
+
8
+ List <Integer > res = new ArrayList <>();
9
+
10
+ while (root1 != null || root2 != null || !st1 .empty () || !st2 .empty ()){
11
+ while (root1 != null ){
12
+ st1 .push (root1 );
13
+ root1 = root1 .left ;
14
+ }
15
+ while (root2 != null ){
16
+ st2 .push (root2 );
17
+ root2 = root2 .left ;
18
+ }
19
+ if (st2 .empty () || (!st1 .empty () && st1 .peek ().val <= st2 .peek ().val )){
20
+ root1 = st1 .pop ();
21
+ res .add (root1 .val );
22
+ root1 = root1 .right ;
23
+ }
24
+ else {
25
+ root2 = st2 .pop ();
26
+ res .add (root2 .val );
27
+ root2 = root2 .right ;
28
+ }
29
+ }
30
+ return res ;
11
31
}
12
- Arrays .sort (arr );
13
- List <Integer > now = new ArrayList <>();
14
- for (int j : arr ){
15
- now .add (j );
16
- }
17
- return now ;
18
- }
19
- public void there (TreeNode root , List <Integer > map ){
20
- if (root ==null ){
21
- return ;
22
- }
23
- map .add (root .val );
24
- if (root .left !=null ){
25
- there (root .left , map );
26
- }
27
- if (root .right !=null ){
28
- there (root .right , map );
29
- }
30
- }
31
- }
32
+ }
You can’t perform that action at this time.
0 commit comments