File tree 1 file changed +67
-0
lines changed
1 file changed +67
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * @lc app=leetcode.cn id=1305 lang=javascript
3
+ *
4
+ * [1305] 两棵二叉搜索树中的所有元素
5
+ *
6
+ * 1. 中序遍历二叉搜索树, 得到结果是从小到大排好序的
7
+ * 2. 然后问题就变成了两个有序数组合并问题
8
+ */
9
+
10
+ // @lc code=start
11
+ /**
12
+ * Definition for a binary tree node.
13
+ * function TreeNode(val) {
14
+ * this.val = val;
15
+ * this.left = this.right = null;
16
+ * }
17
+ */
18
+ /**
19
+ * @param {TreeNode } root1
20
+ * @param {TreeNode } root2
21
+ * @return {number[] }
22
+ */
23
+ var getAllElements = function ( root1 , root2 ) {
24
+ function getArray ( tree ) {
25
+ const result = [ ] ;
26
+ function left ( node ) {
27
+ if ( node . left ) {
28
+ left ( node . left ) ;
29
+ }
30
+ result . push ( node . val ) ;
31
+ if ( node . right ) {
32
+ left ( node . right ) ;
33
+ }
34
+ }
35
+ if ( tree ) {
36
+ left ( tree ) ;
37
+ }
38
+ return result ;
39
+ }
40
+
41
+ const array1 = getArray ( root1 ) ;
42
+ const array2 = getArray ( root2 ) ;
43
+
44
+ const result = [ ] ;
45
+ let a = 0 ;
46
+ let b = 0 ;
47
+ while ( a < array1 . length && b < array2 . length ) {
48
+ if ( array1 [ a ] < array2 [ b ] ) {
49
+ result . push ( array1 [ a ] ) ;
50
+ a ++ ;
51
+ } else {
52
+ result . push ( array2 [ b ] ) ;
53
+ b ++ ;
54
+ }
55
+ }
56
+ while ( a < array1 . length ) {
57
+ result . push ( array1 [ a ] ) ;
58
+ a ++ ;
59
+ }
60
+ while ( b < array2 . length ) {
61
+ result . push ( array2 [ b ] ) ;
62
+ b ++ ;
63
+ }
64
+
65
+ return result ;
66
+ } ;
67
+ // @lc code=end
You can’t perform that action at this time.
0 commit comments