2020년/코테

[코테 연습] All Elements in Two Binary Search Trees

위지원 2020. 9. 16. 16:30

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

 

All Elements in Two Binary Search Trees - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Given two binary search trees root1 and root2.

Return a list containing all the integers from both trees sorted in ascending order.

 


 

아예 트리를 주지 않는 경우가 있었다.. ㄴㅇㄱ

 

# 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 search(self, root, res):
if root == "null":
return
res.append(root.val)
root.val = "null"
if root.left:
self.search(root.left,res)
if root.right:
self.search(root.right,res)
return res
def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
if root1 is None:
return sorted(self.search(root2,[]))
if root2 is None:
return sorted(self.search(root1,[]))
res1 = self.search(root1,[])
res2 = self.search(root2,[])
return sorted(res1+res2)