Source From Here
QuestionGiven two binary search trees root1 and root2.
Return a list containing all the integers from both trees sorted in ascending order:
Constraints:
Solution
Naive
- # 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]:
- # 1) Collecting values of two trees
- list1 = []
- list2 = []
- def inorder(node, alist):
- if node is None:
- return
- if node.left:
- inorder(node.left, alist)
- alist.append(node.val)
- if node.right:
- inorder(node.right, alist)
- inorder(root1, list1)
- inorder(root2, list2)
- # 2) Conducting mergesort
- rlist = []
- while list1 and list2:
- if list1[0] < list2[0]:
- rlist.append(list1.pop(0))
- else:
- rlist.append(list2.pop(0))
- if list1:
- rlist.extend(list1)
- if list2:
- rlist.extend(list2)
- return rlist
Discussion (link)
- class Solution:
- def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
- def gen(node):
- if node:
- yield from gen(node.left)
- yield node.val
- yield from gen(node.right)
- return list(heapq.merge(gen(root1), gen(root2)))
Supplement
* FAQ - In practice, what are the main uses for the new "yield from" syntax in Python 3.3?
沒有留言:
張貼留言