给你 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


    1. /**
    2. * Definition for a binary tree node.
    3. * public class TreeNode {
    4. * int val;
    5. * TreeNode left;
    6. * TreeNode right;
    7. * TreeNode() {}
    8. * TreeNode(int val) { this.val = val; }
    9. * TreeNode(int val, TreeNode left, TreeNode right) {
    10. * this.val = val;
    11. * this.left = left;
    12. * this.right = right;
    13. * }
    14. * }
    15. */
    16. class Solution {
    17. public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
    18. List<Integer> list1 = new ArrayList<>();
    19. List<Integer> list2 = new ArrayList<>();
    20. dfs(root1, list1);
    21. dfs(root2, list2);
    22. List<Integer> res = new ArrayList<>();
    23. int n = list1.size(), m = list2.size();
    24. for (int l = 0, r = 0; l < n || r < m; ) {
    25. if (l >= n) {
    26. res.add(list2.get(r ++));
    27. continue;
    28. }
    29. if (r >= m) {
    30. res.add(list1.get(l ++));
    31. continue;
    32. }
    33. if (list1.get(l) <= list2.get(r)) res.add(list1.get(l ++));
    34. else res.add(list2.get(r ++));
    35. }
    36. return res;
    37. }
    38. void dfs(TreeNode root, List<Integer> list) {
    39. if (root == null) return;
    40. dfs(root.left, list);
    41. list.add(root.val);
    42. dfs(root.right, list);
    43. }
    44. }