码迷,mamicode.com
首页 > 其他好文 > 详细

1305. All Elements in Two Binary Search Trees

时间:2020-02-06 10:51:59      阅读:43      评论:0      收藏:0      [点我收藏+]

标签:list   tput   amp   pre   void   val   int   get   ==   

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

标签:list   tput   amp   pre   void   val   int   get   ==   

原文地址:https://www.cnblogs.com/beiyeqingteng/p/12267651.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!