【力扣】1305:兩顆二叉搜索樹中的所有元素

給你 root1 和 root2 這兩棵二叉搜索樹。
請你返回一個列表,其中包含 兩棵樹 中的所有整數並按 升序 排序。.

算法

一個函數來取得二叉搜索樹的值,爲了方便後面的結合,所以反向取得。

        def helper(r,t=[]):
            if not r:return t
            t=helper(r.right,t)
            t.append(r.val)
            t=helper(r.left,t)
            return t
class Solution:
    def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
        def helper(r,t=[]):
            if not r:return t
            t=helper(r.right,t)
            t.append(r.val)
            t=helper(r.left,t)
            return t
        l1=helper(root1,[])
        l2=helper(root2,[])
        # return l1,l2
        res=[]
        while l1 and l2:
            if l1[-1]<l2[-1]:
                res.append(l1.pop())
            else:res.append(l2.pop())
        # return res
        return res+l1[::-1] if l1 else res+l2[::-1]

執行用時 :376 ms, 在所有 Python3 提交中擊敗了82.18%的用戶
內存消耗 :21.5 MB, 在所有 Python3 提交中擊敗了7.69%的用戶

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章