1305. All Elements in Two Binary Search Trees

Posted beiyeqingteng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1305. All Elements in Two Binary Search Trees相关的知识,希望对你有一定的参考价值。

Given two binary search trees root1 and root2.

Return a list containing all the integers from both trees sorted in ascending order.

 

Example 1:

技术图片

Input: root1 = [2,1,4], root2 = [1,0,3]
Output: [0,1,1,2,3,4]

Example 2:

Input: root1 = [0,-10,10], root2 = [5,1,7,0,2]
Output: [-10,0,0,1,2,5,7,10]

Example 3:

Input: root1 = [], root2 = [5,1,7,0,2]
Output: [0,1,2,5,7]

Example 4:

Input: root1 = [0,-10,10], root2 = []
Output: [-10,0,10]

Example 5:

技术图片

Input: root1 = [1,null,8], root2 = [8,1]
Output: [1,1,8,8]

 1 class Solution {
 2     public static void dfs(TreeNode root, List<Integer> list){
 3         if(root == null) return;
 4         dfs(root.left, list);
 5         list.add(root.val);
 6         dfs(root.right, list);
 7     }
 8     public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
 9         List<Integer> ans = new ArrayList<>();
10         List<Integer> l1 = new ArrayList<>();
11         List<Integer> l2 = new ArrayList<>();
12         dfs(root1, l1);
13         dfs(root2, l2);
14         int i1 = 0, i2 = 0;
15         while(i1 < l1.size() || i2 < l2.size()){
16             if(i2 == l2.size() || i1 < l1.size() && l1.get(i1) <= l2.get(i2)){
17                 ans.add(l1.get(i1));
18                 i1++;
19             } else {
20                 ans.add(l2.get(i2));
21                 i2++;
22             }
23         }
24         return ans;
25     }
26 }

 

以上是关于1305. All Elements in Two Binary Search Trees的主要内容,如果未能解决你的问题,请参考以下文章

leetcode1464. Maximum Product of Two Elements in an Array

LeetCode --- 1464. Maximum Product of Two Elements in an Array 解题报告

LeetCode --- 1464. Maximum Product of Two Elements in an Array 解题报告

Leetcode 1464. Maximum Product of Two Elements in an Array

Leetcode 1464. Maximum Product of Two Elements in an Array

GitHub Two-Factor Authentication All In One