给你 root1 和 root2 这两棵二叉搜索树。请你返回一个列表,其中包含 两棵树 中的所有整数并按 升序 排序。.
示例 1:
输入:root1 = [2,1,4], root2 = [1,0,3]
输出:[0,1,1,2,3,4]
示例 2:
输入:root1 = [1,null,8], root2 = [8,1]
输出:[1,1,8,8]
提示:
每棵树的节点数在 [0, 5000] 范围内
-105 <= Node.val <= 105
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
List<Integer> list1 = new ArrayList<>();
List<Integer> list2 = new ArrayList<>();
dfs(root1, list1);
dfs(root2, list2);
List<Integer> res = new ArrayList<>();
int n = list1.size(), m = list2.size();
for (int l = 0, r = 0; l < n || r < m; ) {
if (l >= n) {
res.add(list2.get(r ++));
continue;
}
if (r >= m) {
res.add(list1.get(l ++));
continue;
}
if (list1.get(l) <= list2.get(r)) res.add(list1.get(l ++));
else res.add(list2.get(r ++));
}
return res;
}
void dfs(TreeNode root, List<Integer> list) {
if (root == null) return;
dfs(root.left, list);
list.add(root.val);
dfs(root.right, list);
}
}