好久没刷题了,好不容易闲了下来回来刷道题。我现在用的是python
题目:
Given two binary search trees root1
and root2
.
Return a list containing all the integers from both trees sorted in ascending order
这道题很简单,只需要中序遍历就可以。我开始居然TLE了,后来发现是我遍历的时候把值放在dict里作为key,然后value作为出现次数,最后把值从sorted keys中放到list里去,这样最后一个test case过不去。后来我直接append到list中去,然后最后sort list输出就可以了,这个时间应该就是差在最后复制到list中的时间吧,竟然就会超时。
代码:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def getAllElements(self, root1, root2):
"""
:type root1: TreeNode
:type root2: TreeNode
:rtype: List[int]
"""
dict_all = {}
result_all = []
for test in range(2):
if test==0:
this_node = root1
else:
this_node = root2
self.dfs(this_node, result_all)
result_all.sort()
return result_all
def dfs(self, this_node, result_all):
if this_node is None:
return
self.dfs(this_node.left, result_all)
val = this_node.val
result_all.append(val)
self.dfs(this_node.right, result_all)