LeetCode 1305 All Elements in Two Binary Search Trees
好久沒刷題了,好不容易閒了下來回來刷道題。我現在用的是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)
相關文章
- 【LeetCode】617. Merge Two Binary TreesLeetCode
- LeetCode 617. Merge Two Binary TreesLeetCode
- LeetCode之All Possible Full Binary Trees(Kotlin)LeetCodeKotlin
- 617-Merge Two Binary Trees
- 題解:CF1237E Balanced Binary Search Trees
- LeetCode 98. Validate Binary Search TreeLeetCode
- [LeetCode] 501. Find Mode in Binary Search TreeLeetCode
- [leetcode]convert-sorted-array-to-binary-search-treeLeetCode
- LeetCode 501. Find Mode in Binary Search TreeLeetCode
- [LeetCode] 109. Convert Sorted List to Binary Search TreeLeetCode
- Java for LeetCode 109 Convert Sorted List to Binary Search TreeJavaLeetCode
- 96-Unique Binary Search Trees 二叉搜尋樹的數量
- go Exercise: Equivalent Binary TreesGoUI
- LeetCode C++ 441. Arranging Coins【Math/Binary Search】簡單LeetCodeC++
- LeetCode C++ 1464. Maximum Product of Two Elements in an Array【Array/Sort】簡單LeetCodeC++
- 669-Trim a Binary Search Tree
- 173. Binary Search Tree Iterator
- 501-Find Mode in Binary Search Tree
- Leetcode Word SearchLeetCode
- 108-Convert Sorted Array to Binary Search Tree
- 235-Lowest Common Ancestor of a Binary Search Tree
- CF1945E Binary Search 題解
- Leetcode 231 Power of TwoLeetCode
- Leetcode 1 two sumLeetCode
- LeetCode | 1 Two SumLeetCode
- LeetCode之Leaf-Similar Trees(Kotlin)LeetCodeMILAKotlin
- Leetcode 67 Add BinaryLeetCode
- Leetcode Binary Tree PathsLeetCode
- 二分查詢法(Binary_Search)
- 二分搜尋樹(Binary Search Tree)
- Leetcode 29 Divide Two IntegersLeetCodeIDE
- LeetCode 2 Add Two NumbersLeetCode
- LeetCode-1 Two SumLeetCode
- [LeetCode]1.Two SumLeetCode
- LeetCode | 349 Intersection Of Two ArraysLeetCode
- Leetcode 231. Power of TwoLeetCode
- python: leetcode - 1 Two SumPythonLeetCode
- binary_search只回答序列裡是否存在val