[leetcode #1305] All Elements in Two Binary Search Trees


Problem


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 = [1,null,8], root2 = [8,1]
Output: [1,1,8,8]
Constraints:
・ The number of nodes in each tree is in the range [0, 5000].
・ -10⁵ <= Node.val <= 10⁵

Idea


帰依主義が限界に達した時に解決した問題だ.
Stackを使う方法、Priority Queueを使う方法などがありますが、私は2つのBSTでナビゲートして1つのリストに入れて、最後に並べ替えて解くだけです.(Time comlexity - O(nlogn))
問題をより効果的に解決するには、BSTを2つのリストに挿入し、リストを再参照し、サイズを比較し、新しいリストに追加します.(Time complexity - O(n))

Solution

/**
 * 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 {
    private List<Integer> res;

    public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
        res = new ArrayList<Integer>();

        traverseTree(root1);
        traverseTree(root2);
        Collections.sort(res);

        return res;
    }

    private void traverseTree(TreeNode node) {
        if (node == null) {
            return;
        }

        traverseTree(node.left);
        res.add(node.val);
        traverseTree(node.right);
    }
}

Reference


https://leetcode.com/problems/all-elements-in-two-binary-search-trees/