動機

應該可以改成iterator各自的BST,但很麻煩,就直接攤平吧

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,Leetcode,8], root2 = [8,1]Output: [1,1,8,8]

 

Constraints:

  • The number of nodes in each tree is in the range [0, 5000].
  • -105 <= Node.val <= 105

sol

from heapq import merge
class Solution:
    def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
        ret = []
        def walk(r, acc):
            if r:
                tmp = walk(r.left, acc)
                tmp.append(r.val)
                return walk(r.right, tmp)
            else:
                return acc
        return list(merge(walk(root1,[]), walk(root2,[])))