The title

I give you two binary search trees root1 and root2.

Return a list of all integers in 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 = [0,-10,10], root2 = [5,1,7,0,2] output: 10,0,0,1,2,5,7,10 [-] example 3: input: [] = root1, root2 =,1,7,0,2 [5] output:,1,2,5,7 [0] example 4: input: root1 = [0, 10, 10], root2 = [] output: 10,0,10] [-Copy the code

Example 5: Input: root1 = [1, NULL,8], root2 = [8,1] Output: [1,1,8,8]Copy the code

Tip:

Each tree has a maximum of 5000 nodes. Each node has a value between [-10^5, 10^5].

Their thinking

# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]: resList = [] # def DFS (root:TreeNode): if root == None: return resList.append(root.val) if root.left: dfs(root.left) if root.right: dfs(root.right) dfs(root1) dfs(root2) resList.sort() return resList if __name__ == '__main__': root1 = TreeNode(1) root1.left = TreeNode(2) root1.right = TreeNode(3) root2 = TreeNode(3) root2.left = TreeNode(4) root2.right = TreeNode(5) result = Solution().getAllElements(root1, root2) print(result)Copy the code