5959
6060<!-- solution:start -->
6161
62- ### 方法一
62+ ### 方法一:DFS + 归并
63+
64+ 由于两棵树都是二叉搜索树,所以我们可以通过中序遍历得到两棵树的节点值序列 $\textit{a}$ 和 $\textit{b}$,然后使用双指针归并两个有序数组,得到最终的答案。
65+
66+ 时间复杂度 $O(n+m)$,空间复杂度 $O(n+m)$。其中 $n$ 和 $m$ 分别是两棵树的节点数。
6367
6468<!-- tabs:start -->
6569
@@ -73,36 +77,36 @@ tags:
7377# self.left = left
7478# self.right = right
7579class Solution :
76- def getAllElements (self , root1 : TreeNode, root2 : TreeNode) -> List[int ]:
77- def dfs (root , t ):
80+ def getAllElements (
81+ self , root1 : Optional[TreeNode], root2 : Optional[TreeNode]
82+ ) -> List[int ]:
83+ def dfs (root : Optional[TreeNode], nums : List[int ]) -> int :
7884 if root is None :
7985 return
80- dfs(root.left, t)
81- t.append(root.val)
82- dfs(root.right, t)
83-
84- def merge (t1 , t2 ):
85- ans = []
86- i = j = 0
87- while i < len (t1) and j < len (t2):
88- if t1[i] <= t2[j]:
89- ans.append(t1[i])
90- i += 1
91- else :
92- ans.append(t2[j])
93- j += 1
94- while i < len (t1):
95- ans.append(t1[i])
86+ dfs(root.left, nums)
87+ nums.append(root.val)
88+ dfs(root.right, nums)
89+
90+ a, b = [], []
91+ dfs(root1, a)
92+ dfs(root2, b)
93+ m, n = len (a), len (b)
94+ i = j = 0
95+ ans = []
96+ while i < m and j < n:
97+ if a[i] <= b[j]:
98+ ans.append(a[i])
9699 i += 1
97- while j < len (t2) :
98- ans.append(t2 [j])
100+ else :
101+ ans.append(b [j])
99102 j += 1
100- return ans
101-
102- t1, t2 = [], []
103- dfs(root1, t1)
104- dfs(root2, t2)
105- return merge(t1, t2)
103+ while i < m:
104+ ans.append(a[i])
105+ i += 1
106+ while j < n:
107+ ans.append(b[j])
108+ j += 1
109+ return ans
106110```
107111
108112#### Java
@@ -125,40 +129,37 @@ class Solution:
125129 */
126130class Solution {
127131 public List<Integer > getAllElements (TreeNode root1 , TreeNode root2 ) {
128- List<Integer > t1 = new ArrayList<> ();
129- List<Integer > t2 = new ArrayList<> ();
130- dfs(root1, t1);
131- dfs(root2, t2);
132- return merge(t1, t2);
133- }
134-
135- private void dfs (TreeNode root , List<Integer > t ) {
136- if (root == null ) {
137- return ;
138- }
139- dfs(root. left, t);
140- t. add(root. val);
141- dfs(root. right, t);
142- }
143-
144- private List<Integer > merge (List<Integer > t1 , List<Integer > t2 ) {
145- List<Integer > ans = new ArrayList<> ();
132+ List<Integer > a = new ArrayList<> ();
133+ List<Integer > b = new ArrayList<> ();
134+ dfs(root1, a);
135+ dfs(root2, b);
136+ int m = a. size(), n = b. size();
146137 int i = 0 , j = 0 ;
147- while (i < t1. size() && j < t2. size()) {
148- if (t1. get(i) <= t2. get(j)) {
149- ans. add(t1. get(i++ ));
138+ List<Integer > ans = new ArrayList<> ();
139+ while (i < m && j < n) {
140+ if (a. get(i) <= b. get(j)) {
141+ ans. add(a. get(i++ ));
150142 } else {
151- ans. add(t2 . get(j++ ));
143+ ans. add(b . get(j++ ));
152144 }
153145 }
154- while (i < t1 . size() ) {
155- ans. add(t1 . get(i++ ));
146+ while (i < m ) {
147+ ans. add(a . get(i++ ));
156148 }
157- while (j < t2 . size() ) {
158- ans. add(t2 . get(j++ ));
149+ while (j < n ) {
150+ ans. add(b . get(j++ ));
159151 }
160152 return ans;
161153 }
154+
155+ private void dfs (TreeNode root , List<Integer > nums ) {
156+ if (root == null ) {
157+ return ;
158+ }
159+ dfs(root. left, nums);
160+ nums. add(root. val);
161+ dfs(root. right, nums);
162+ }
162163}
163164```
164165
@@ -179,33 +180,36 @@ class Solution {
179180class Solution {
180181public:
181182 vector<int > getAllElements(TreeNode* root1, TreeNode* root2) {
182- vector<int > t1;
183- vector<int > t2;
184- dfs(root1, t1);
185- dfs(root2, t2);
186- return merge(t1, t2);
187- }
183+ vector<int > a, b, ans;
184+ dfs(root1, a);
185+ dfs(root2, b);
188186
189- void dfs(TreeNode* root, vector<int>& t) {
190- if (!root) return;
191- dfs(root->left, t);
192- t.push_back(root->val);
193- dfs(root->right, t);
194- }
195-
196- vector<int > merge (vector<int >& t1, vector<int >& t2) {
197- vector<int > ans;
198187 int i = 0, j = 0;
199- while (i < t1.size() && j < t2.size()) {
200- if (t1[ i] <= t2[ j] )
201- ans.push_back(t1[ i++] );
202- else
203- ans.push_back(t2[ j++] );
188+ while (i < a.size() && j < b.size()) {
189+ if (a[i] <= b[j]) {
190+ ans.push_back(a[i++]);
191+ } else {
192+ ans.push_back(b[j++]);
193+ }
194+ }
195+ while (i < a.size()) {
196+ ans.push_back(a[i++]);
197+ }
198+ while (j < b.size()) {
199+ ans.push_back(b[j++]);
204200 }
205- while (i < t1.size()) ans.push_back(t1[ i++] );
206- while (j < t2.size()) ans.push_back(t2[ j++] );
207201 return ans;
208202 }
203+
204+ private:
205+ void dfs(TreeNode* root, vector<int >& nums) {
206+ if (root == nullptr) {
207+ return;
208+ }
209+ dfs(root->left, nums);
210+ nums.push_back(root->val);
211+ dfs(root->right, nums);
212+ }
209213};
210214```
211215
@@ -220,42 +224,37 @@ public:
220224 * Right *TreeNode
221225 * }
222226 */
223- func getAllElements(root1 *TreeNode, root2 *TreeNode) []int {
224- var dfs func(root *TreeNode) []int
225- dfs = func(root *TreeNode) []int {
227+ func getAllElements (root1 *TreeNode , root2 *TreeNode ) ( ans []int ) {
228+ var dfs func (*TreeNode, * []int )
229+ dfs = func (root *TreeNode, nums * []int ) {
226230 if root == nil {
227- return []int{}
231+ return
228232 }
229- left := dfs(root.Left)
230- right := dfs(root.Right)
231- left = append(left, root.Val)
232- left = append(left, right...)
233- return left
233+ dfs (root.Left , nums)
234+ *nums = append (*nums, root.Val )
235+ dfs (root.Right , nums)
234236 }
235- merge := func(t1, t2 []int) []int {
236- var ans []int
237- i, j := 0, 0
238- for i < len(t1) && j < len(t2) {
239- if t1[i] <= t2[j] {
240- ans = append(ans, t1[i])
241- i++
242- } else {
243- ans = append(ans, t2[j])
244- j++
245- }
246- }
247- for i < len(t1) {
248- ans = append(ans, t1[i])
237+ a , b := []int {}, []int {}
238+ dfs (root1, &a)
239+ dfs (root2, &b)
240+ i , j := 0 , 0
241+ m , n := len (a), len (b)
242+ for i < m && j < n {
243+ if a[i] < b[j] {
244+ ans = append (ans, a[i])
249245 i++
250- }
251- for j < len(t2) {
252- ans = append(ans, t2[j])
246+ } else {
247+ ans = append (ans, b[j])
253248 j++
254249 }
255- return ans
256250 }
257- t1, t2 := dfs(root1), dfs(root2)
258- return merge(t1, t2)
251+ for ; i < m; i++ {
252+ ans = append (ans, a[i])
253+ }
254+ for ; j < n; j++ {
255+ ans = append (ans, b[j])
256+ }
257+ return
259258}
260259```
261260
@@ -277,31 +276,35 @@ func getAllElements(root1 *TreeNode, root2 *TreeNode) []int {
277276 */
278277
279278function getAllElements(root1 : TreeNode | null , root2 : TreeNode | null ): number [] {
280- const res = [];
281- const stacks = [[], []];
282- while (root1 != null || stacks [0 ].length !== 0 || root2 != null || stacks [1 ].length !== 0 ) {
283- if (root1 != null ) {
284- stacks [0 ].push (root1 );
285- root1 = root1 .left ;
286- } else if (root2 != null ) {
287- stacks [1 ].push (root2 );
288- root2 = root2 .left ;
279+ const dfs = (root : TreeNode | null , nums : number []) => {
280+ if (! root ) {
281+ return ;
282+ }
283+ dfs (root .left , nums );
284+ nums .push (root .val );
285+ dfs (root .right , nums );
286+ };
287+ const a: number [] = [];
288+ const b: number [] = [];
289+ dfs (root1 , a );
290+ dfs (root2 , b );
291+ const [m, n] = [a .length , b .length ];
292+ const ans: number [] = [];
293+ let [i, j] = [0 , 0 ];
294+ while (i < m && j < n ) {
295+ if (a [i ] < b [j ]) {
296+ ans .push (a [i ++ ]);
289297 } else {
290- if (
291- (stacks [0 ][stacks [0 ].length - 1 ] ?? { val: Infinity }).val <
292- (stacks [1 ][stacks [1 ].length - 1 ] ?? { val: Infinity }).val
293- ) {
294- const { val, right } = stacks [0 ].pop ();
295- res .push (val );
296- root1 = right ;
297- } else {
298- const { val, right } = stacks [1 ].pop ();
299- res .push (val );
300- root2 = right ;
301- }
298+ ans .push (b [j ++ ]);
302299 }
303300 }
304- return res ;
301+ while (i < m ) {
302+ ans .push (a [i ++ ]);
303+ }
304+ while (j < n ) {
305+ ans .push (b [j ++ ]);
306+ }
307+ return ans ;
305308}
306309```
307310
@@ -333,41 +336,46 @@ impl Solution {
333336 root1 : Option <Rc <RefCell <TreeNode >>>,
334337 root2 : Option <Rc <RefCell <TreeNode >>>,
335338 ) -> Vec <i32 > {
336- fn dfs (root : & Option <Rc <RefCell <TreeNode >>>, t : & mut Vec <i32 >) {
337- if let Some (root ) = root {
338- dfs (& root . borrow (). left, t );
339- t . push (root . borrow (). val);
340- dfs (& root . borrow (). right, t );
341- }
342- }
339+ let mut a = Vec :: new ();
340+ let mut b = Vec :: new ();
343341
344- let mut t1 = Vec :: new ();
345- let mut t2 = Vec :: new ();
346- dfs (& root1 , & mut t1 );
347- dfs (& root2 , & mut t2 );
342+ Solution :: dfs (& root1 , & mut a );
343+ Solution :: dfs (& root2 , & mut b );
348344
349345 let mut ans = Vec :: new ();
350- let mut i = 0 ;
351- let mut j = 0 ;
352- while i < t1 . len () && j < t2 . len () {
353- if t1 [i ] < t2 [j ] {
354- ans . push (t1 [i ]);
346+ let ( mut i , mut j ) = ( 0 , 0 ) ;
347+
348+ while i < a . len () && j < b . len () {
349+ if a [i ] <= b [j ] {
350+ ans . push (a [i ]);
355351 i += 1 ;
356352 } else {
357- ans . push (t2 [j ]);
353+ ans . push (b [j ]);
358354 j += 1 ;
359355 }
360356 }
361- while i < t1 . len () {
362- ans . push (t1 [i ]);
357+
358+ while i < a . len () {
359+ ans . push (a [i ]);
363360 i += 1 ;
364361 }
365- while j < t2 . len () {
366- ans . push (t2 [j ]);
362+
363+ while j < b . len () {
364+ ans . push (b [j ]);
367365 j += 1 ;
368366 }
367+
369368 ans
370369 }
370+
371+ fn dfs (root : & Option <Rc <RefCell <TreeNode >>>, nums : & mut Vec <i32 >) {
372+ if let Some (node ) = root {
373+ let node = node . borrow ();
374+ Solution :: dfs (& node . left, nums );
375+ nums . push (node . val);
376+ Solution :: dfs (& node . right, nums );
377+ }
378+ }
371379}
372380```
373381
0 commit comments