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 }

 

posted @ 2020-02-06 09:39  北叶青藤  阅读(524)  评论(0编辑  收藏  举报