Vai al contenuto principale
ProdottiStrumenti desktopTASTECADVisualizzazione disegniTASTEFILESGestione fileTASTEFTPTrasferimento fileTASTESSHSpazio di lavoro remotoTASTEZIPCompressione ed estrazioneTASTEWINMGestione fileStrumenti per sviluppatoriTASTECODEAmbiente di sviluppo integrato per RustTASTESTUDIOAmbiente integrato di sviluppo e testTASTEETLIntegrazione dati (ETL)ServerTASTEREMOTEServer di desktop remotoTASTEGEOServer geospazialeTASTEMAILSpazio di lavoro emailInvestimentiTASTESTOCKApp desktop di trading automatico azionarioIniziaDownloadDocumentazioneAcquistaTutti i prodotti
Marketplace
Notizie
TecnologiaNotizieNotizie di sviluppo di oggiDocumentazioneLinguaggi di programmazioneRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFramework frontend webNext.jsReactVue.js · NuxtSvelteKitAngularFramework serverSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFramework per app e desktopTauriFlutterReact NativeElectronAlgoritmiBasi degli algoritmiAlgoritmi fondamentaliAlgoritmi avanzatiAlgoritmi pratici
CommunityProgettiLog di sviluppoPromptProblemi degli strumenti di IAVetrinaGuida alla community
CollaboraTrasferimento tecnicoRealizzazione del sito webRealizzazione di app desktopPipeline di rilascio e pagamentoPartner commercialeContatti
ServiziDesktop remotoPacchetti di installazione su misura
TASTEDEV
Prodotti

Strumenti desktop

TASTECADApri con leggerezza anche i disegni più complessiTASTEFILESSolo i file che servono, alla massima velocitàTASTEFTPLa via più ordinata per i tuoi fileTASTESSHUn legame più solido tra te e i tuoi serverTASTEZIPComprimi più veloce, estrai più sicuroTASTEWINMUn file manager a due pannelli pensato per la tastiera

Strumenti per sviluppatori

TASTECODEModifica, compila, esegui il debug e testa app Rust in un'unica finestraTASTESTUDIODalla modifica ai test remoti e alle correzioni IA approvateTASTEETLSposta i dati guardando i valori

Server

TASTEREMOTEUn desktop remoto che gira sul tuo serverTASTEGEOUn server geospaziale compatibile con GeoServer, ricostruito in RustTASTEMAILRiprendi il controllo della tua posta

Investimenti

TASTESTOCKTrading automatico azionario secondo le regole che decidi tu: quando e che cosa

Inizia

DownloadUltime versioni di ogni prodottoDocsCome usare ogni prodottoAcquistaAbbonamenti e licenze perpetueTutti i prodottiTutti i prodotti a colpo d’occhio
Tutti i prodotti
MarketplaceNotizie
Tecnologia

Notizie

Notizie di sviluppo di oggiAnnunci ufficiali su linguaggi, framework, GitHub e IADocumentazioneGuide a linguaggi, framework e algoritmi

Linguaggi di programmazione

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Framework

Framework frontend webNext.jsReactVue.js · NuxtSvelteKitAngular
Framework serverSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Framework per app e desktopTauriFlutterReact NativeElectron

Algoritmi

Basi degli algoritmiAnalisi della complessità · Ordinamento · Ricerca · Strutture dati di base · Alberi e heapAlgoritmi fondamentaliVisita dei grafi · Cammini minimi e alberi ricoprenti · Programmazione dinamica · Algoritmi greedy · Divide et impera · BacktrackingAlgoritmi avanzatiAlgoritmi sulle stringhe · Matematica e teoria dei numeri · Manipolazione dei bit · Alberi di segmenti · Union-FindAlgoritmi praticiStrategia per colloqui di programmazione · Cache LRU · Rate limiting · Hashing consistente
Tutta la documentazione di sviluppo
Community
ProgettiScopri sviluppatori e lavoriLog di sviluppoDecisioni e lezioni appresePromptIstruzioni riutilizzabiliProblemi degli strumenti di IAProblemi e alternative di Claude, Codex, GeminiVetrinaRisultati completatiGuida alla communityCome sviluppiamo in modo aperto
Collabora
Trasferimento tecnicoApp native in Rust ed eguiRealizzazione del sito web10 lingue, account, documentazione e downloadRealizzazione di app desktopRust ed egui, senza WebViewPipeline di rilascio e pagamentoFirma, MSI, deb, rpm, AppImage, hashPartner commercialeConsigliaci e ricevi il 30%ContattiSviluppo, partnership e investimenti
Servizi
Desktop remotoRaggiungi il tuo computer dal browserPacchetti di installazione su misuraSolo il necessario, impostazioni precaricate
Acquista
IT
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Accedi
Accedi
TASTEDEV

Dai piccoli strumenti a uno sviluppo migliore.

support@tastedev.netSostieni TASTEDEV
ProdottiGamma di prodottiAcquistaDocsDownloadMarketplaceAssistenza
CommunityProgettiLog di sviluppoPromptProblemi degli strumenti di IAVetrina
NormeChi siamoInformativa sulla privacyTermini di servizioCondizioni di abbonamentoRimborsiLinee guida della community
AccountAccediRegistrati
Visitatori
Oggi
Ieri
Visualizzazioni totali
Società
GXSOFT
Rappresentante
CHOI YOUNG GU
Numero di registrazione
853-44-00368
Indirizzo
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Telefono
+82-10-4404-1523
E-mail
whitecalvin@tastedev.net
Responsabile privacy
CHOI YOUNG GU

© 2026 TASTEDEVLe informazioni sui prodotti si basano su fonti di sviluppo verificate.Rilasciato · in miglioramento

Documentazione di Alberi e heap
Alberi e heap
Tree and Heap ConceptsHow It WorksImplementationComplexityPractice ProblemsTrees and Heaps in the Real World
Discussioni

Guida a Alberi e heap · 5/6

Practice Problems

Per ora questo capitolo è disponibile solo in inglese.

Tree and heap questions are staples of coding interviews and online assessments. The four problems below each cover one classic pattern: traversal by level, using the BST property, a size-limited heap, and merging with a heap. Think about an approach first, then compare with the solution. All the code shares this Node definition.

class Node:
    def __init__(self, key, left=None, right=None):
        self.key, self.left, self.right = key, left, right

Problem 1. Largest value on each level

Given a binary tree, return a list with the largest key at each depth, from the root downward. An empty tree gives an empty list. For example, with root 4, children 9 and 2, and grandchildren 3, 5 and 7, the answer is [4, 9, 7].

Approach: grouping by depth points to a level-order traversal. Popping exactly "the current queue length" items at a time processes one level per round. Time is O(n); space is the size of the widest level.

from collections import deque


def level_maxima(root):
    if root is None:
        return []
    result, queue = [], deque([root])
    while queue:
        best = None
        for _ in range(len(queue)):        # only this level's nodes
            node = queue.popleft()
            best = node.key if best is None else max(best, node.key)
            queue.extend(c for c in (node.left, node.right) if c)
        result.append(best)
    return result


tree = Node(4, Node(9, Node(3), Node(5)), Node(2, None, Node(7)))
print(level_maxima(tree))  # [4, 9, 7]

Problem 2. Range sum in a BST

Given a binary search tree and two integers lo and hi, return the sum of all keys with lo <= key <= hi. Subtrees that are certainly out of range must not be visited.

Approach: prune with the BST property. If the current key is below lo, everything in its left subtree is smaller still, so skip it; if it is above hi, skip the right subtree. The number of visited nodes is roughly O(h + number of matching nodes). An explicit stack keeps deep trees safe.

def range_sum(root, lo, hi):
    total, stack = 0, [root]
    while stack:
        node = stack.pop()
        if node is None:
            continue
        if lo <= node.key <= hi:
            total += node.key
        if node.key > lo:          # the left side may still hold keys >= lo
            stack.append(node.left)
        if node.key < hi:          # the right side may still hold keys <= hi
            stack.append(node.right)
    return total


bst = Node(10, Node(5, Node(3), Node(7)), Node(15, None, Node(18)))
print(range_sum(bst, 6, 15))  # 7 + 10 + 15 = 32

Problem 3. K-th highest score, live

A game server receives scores one at a time. After each score, output the K-th highest score seen so far, or while fewer than K scores have arrived.

Domande su questo capitolo?
Capitolo precedenteComplexityCapitolo successivoTrees and Heaps in the Real World
None

Approach: keep a min-heap capped at K items. It holds only the top K scores, so its root is exactly the K-th highest. When a new score beats the root, replace the root (heapq.heapreplace or heappushpop). Each score costs O(log K) and memory is O(K), far cheaper than sorting everything.

import heapq


def kth_highest_stream(scores, k):
    heap, out = [], []
    for s in scores:
        if len(heap) < k:
            heapq.heappush(heap, s)
        elif s > heap[0]:
            heapq.heapreplace(heap, s)   # pop the root, push s
        out.append(heap[0] if len(heap) == k else None)
    return out


print(kth_highest_stream([40, 10, 70, 20, 90, 50], 3))
# [None, None, 10, 20, 40, 50]

Problem 4. Merging logs from several servers

Each of k servers has a list of (timestamp, message) entries sorted by time. Merge them into one time-ordered list. When timestamps tie, the server with the smaller index goes first.

Approach: keep only the next candidate from each list in a heap. Each time you pop the earliest entry, push the next entry from the same list. Storing (timestamp, server index, position) breaks ties by server index and never compares messages. With N entries in total this is O(N log k). The standard heapq.merge works the same way.

import heapq


def merge_logs(logs):
    heap = [(lst[0][0], i, 0) for i, lst in enumerate(logs) if lst]
    heapq.heapify(heap)
    merged = []
    while heap:
        t, i, j = heapq.heappop(heap)
        merged.append(logs[i][j])
        if j + 1 < len(logs[i]):
            heapq.heappush(heap, (logs[i][j + 1][0], i, j + 1))
    return merged


logs = [
    [(1, "a:start"), (5, "a:done")],
    [(2, "b:start"), (5, "b:retry"), (9, "b:done")],
    [],
    [(3, "d:start")],
]
print([m for _, m in merge_logs(logs)])
# ['a:start', 'b:start', 'd:start', 'a:done', 'b:retry', 'b:done']

Habits for checking a solution

  • Always test an empty tree, a single node, and a tree that leans entirely to one side.
  • Tuples in a heap compare element by element, so never let an incomparable value be reached on a tie.
  • For "K-th largest" keep a min-heap of size K; for "K-th smallest" use a max-heap (negate the values).

Summary

Level-based questions call for level-order traversal, range questions for BST pruning, "top K" for a min-heap of size K, and merging sorted inputs for a heap holding the head of each input. With these four templates you can handle most variations on sight.

0 commenti

Commenti principaliPrima i più recenti

Accedi · Accedi per lasciare un commento.