题目链接:
力扣https://leetcode-cn.com/problems/all-elements-in-two-binary-search-trees/
【分析】dfs中序遍历二叉搜索树后得到的就是从小到大排好序的列表,再用归并排序的思想把两个链表合并即可。
class Solution {
List<Integer> list1 = new ArrayList();
List<Integer> list2 = new ArrayList();
public void dfs(TreeNode root, List<Integer> list){
if(root != null){
dfs(root.left, list);
list.add(root.val);
dfs(root.right, list);
}
}
public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
dfs(root1, list1);
dfs(root2, list2);
int i = 0, j = 0, m = list1.size(), n = list2.size();
int x, y;
List<Integer> ans = new ArrayList();
while(i < m && j < n){
x = list1.get(i);
y = list2.get(j);
if(x < y){
ans.add(x); i++;
}else{
ans.add(y); j++;
}
}
while(i < m) ans.add(list1.get(i++));
while(j < n) ans.add(list2.get(j++));
return ans;
}
}