1305. 两棵二叉搜索树中的所有元素

给你 root1 和 root2 这两棵二叉搜索树。

请你返回一个列表,其中包含 两棵树 中的所有整数并按 升序 排序。.

 

示例 1:

 

输入:root1 = [2,1,4], root2 = [1,0,3]
输出:[0,1,1,2,3,4]
示例 2:

输入:root1 = [0,-10,10], root2 = [5,1,7,0,2]
输出:[-10,0,0,1,2,5,7,10]
示例 3:

输入:root1 = [], root2 = [5,1,7,0,2]
输出:[0,1,2,5,7]
示例 4:

输入:root1 = [0,-10,10], root2 = []
输出:[-10,0,10]
示例 5:

 

输入:root1 = [1,null,8], root2 = [8,1]
输出:[1,1,8,8]
 

提示:

每棵树最多有 5000 个节点。
每个节点的值在 [-10^5, 10^5] 之间。

来源:力扣(LeetCode)

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
        def preorderTraversal(root):
            if not root:return []
            stack, res = [root], []
            while stack:
                root = stack.pop()
                if root:
                    res.append(root.val)
                    if root.right:
                        stack.append(root.right)
                    if root.left:
                        stack.append(root.left)
            return res
        return sorted(preorderTraversal(root1)+preorderTraversal(root2))

 

 

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
        res=[]
        def solve(a):
            if a:
                res.append(a.val)
                solve(a.left)
                solve(a.right)
        return solve(root1) or solve(root2) or sorted(res)

 

posted @ 2020-10-18 11:44  XXXSANS  阅读(113)  评论(0编辑  收藏  举报