给你 root1 和 root2 这两棵二叉搜索树。
请你返回一个列表,其中包含 两棵树 中的所有整数并按 升序 排序。.
示例 1:
输入:root1 = [2,1,4], root2 = [1,0,3]
输出:[0,1,1,2,3,4]
示例 2:
输入:root1 = [0,-10,10], root2 = [5,1,7,0,2]
输出:[-10,0,0,1,2,5,7,10]
示例 3:
输入:root1 = [], root2 = [5,1,7,0,2]
输出:[0,1,2,5,7]
示例 4:
输入:root1 = [0,-10,10], root2 = []
输出:[-10,0,10]
示例 5:
输入:root1 = [1,null,8], root2 = [8,1]
输出:[1,1,8,8]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/all-elements-in-two-binary-search-trees
解题思路:输入的两个树是搜索二叉树(BST),中序遍历得到的数据就是有序的,两个有序的list进行排序最好的方法就是归并排序;当然还可以把两个树无脑的放到list里,使用Collections.sort(list)进行排序,时间复杂度为O(nlogn),没有前者的算法好。
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
List<Integer> list1 = new ArrayList<Integer>();
List<Integer> list2 = new ArrayList<Integer>();
getOneList(root1,list1);
getOneList(root2,list2);
List<Integer> listTotal = new ArrayList<Integer>();
int index1,index2;
int size1 = list1.size();
int size2 = list2.size();
for (index1 = 0,index2=0; index1 < size1 && index2 < size2;) {
Integer int1 = list1.get(index1);
Integer int2 = list2.get(index2);
if(int1>int2){
listTotal.add(int2);
index2++;
}else{
listTotal.add(int1);
index1++;
}
}
while(index1 < size1){
listTotal.add(list1.get(index1++));
}
while(index2 < size2){
listTotal.add(list2.get(index2++));
}
return listTotal;
}
public void getOneList(TreeNode root,List<Integer> list){
if(root == null){
return;
}
getOneList(root.left,list);
list.add(root.val);
getOneList(root.right,list);
}
}
结果: