Zum Hauptinhalt springen
ProdukteDesktop-WerkzeugeTASTECADZeichnungsprüfungTASTEFILESDateiverwaltungTASTEFTPDateiübertragungTASTESSHRemote-ArbeitsbereichTASTEZIPKomprimieren und EntpackenTASTEWINMDateiverwaltungEntwicklerwerkzeugeTASTECODEIntegrierte Entwicklungsumgebung für RustTASTESTUDIOIntegrierte Entwicklungs- und TestumgebungTASTEETLDatenintegration (ETL)ServerTASTEREMOTERemote-Desktop-ServerTASTEGEOGeodatenserverTASTEMAILE-Mail-ArbeitsbereichInvestierenTASTESTOCKDesktop-App für automatischen AktienhandelErste SchritteDownloadsDokumentationKaufenAlle Produkte
Marktplatz
Neuigkeiten
TechnikNeuigkeitenEntwickler-News von heuteEntwicklerdokuProgrammiersprachenRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb-Frontend-FrameworksNext.jsReactVue.js · NuxtSvelteKitAngularServer-FrameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressApp- & Desktop-FrameworksTauriFlutterReact NativeElectronAlgorithmenAlgorithmus-GrundlagenKernalgorithmenFortgeschrittene AlgorithmenAlgorithmen für die Praxis
CommunityProjekteEntwicklungslogsPromptsProbleme mit KI-ToolsShowcaseCommunity-Leitfaden
ZusammenarbeitWissenstransferWebsite-AufbauDesktop-App-AufbauRelease- und ZahlungspipelineVertriebspartnerKontakt
DiensteRemote-DesktopIndividuelle Installationspakete
TASTEDEV
Produkte

Desktop-Werkzeuge

TASTECADKomplexe Zeichnungen, mühelos geöffnetTASTEFILESNur die Dateien, die zählen – in BestzeitTASTEFTPDer aufgeräumteste Weg für Ihre DateienTASTESSHDie stärkere Verbindung zu Ihren ServernTASTEZIPSchneller packen, sicherer entpackenTASTEWINMEin tastaturorientierter Dateimanager mit zwei Fenstern

Entwicklerwerkzeuge

TASTECODERust-Apps bearbeiten, bauen, debuggen und testen – alles in einem FensterTASTESTUDIOVom Bearbeiten bis zu Remote-Tests und freigegebenen KI-KorrekturenTASTEETLDaten bewegen, die Werte im Blick

Server

TASTEREMOTEEin Remote-Desktop auf Ihrem eigenen ServerTASTEGEOEin GeoServer-kompatibler Geodatenserver, neu aufgebaut in RustTASTEMAILIhre E-Mail wieder in Ihrer Hand

Investieren

TASTESTOCKAutomatischer Aktienhandel nach Ihren Regeln: wann und was

Erste Schritte

DownloadsNeueste Versionen aller ProdukteDokuSo nutzen Sie jedes ProduktKaufenAbos und DauerlizenzenAlle ProdukteAlle Produkte im Überblick
Alle Produkte
MarktplatzNeuigkeiten
Technik

Neuigkeiten

Entwickler-News von heuteOffizielle Meldungen zu Sprachen, Frameworks, GitHub und KIEntwicklerdokuAnleitungen zu Sprachen, Frameworks und Algorithmen

Programmiersprachen

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Web-Frontend-FrameworksNext.jsReactVue.js · NuxtSvelteKitAngular
Server-FrameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
App- & Desktop-FrameworksTauriFlutterReact NativeElectron

Algorithmen

Algorithmus-GrundlagenKomplexitätsanalyse · Sortieren · Suchen · Grundlegende Datenstrukturen · Bäume und HeapsKernalgorithmenGraphtraversierung · Kürzeste Wege und minimale Spannbäume · Dynamische Programmierung · Greedy-Algorithmen · Teile und herrsche · BacktrackingFortgeschrittene AlgorithmenZeichenkettenalgorithmen · Mathematik und Zahlentheorie · Bitmanipulation · Segmentbäume · Union-FindAlgorithmen für die PraxisStrategie für Coding-Interviews · LRU-Cache · Rate Limiting · Konsistentes Hashing
Alle Entwicklungsdokumente
Community
ProjekteEntwickler und Projekte entdeckenEntwicklungslogsEntscheidungen und ErkenntnissePromptsWiederverwendbare AnweisungenProbleme mit KI-ToolsProbleme und Workarounds für Claude, Codex, GeminiShowcaseFertige ErgebnisseCommunity-LeitfadenWie wir offen entwickeln
Zusammenarbeit
WissenstransferNative Apps mit Rust und eguiWebsite-Aufbau10 Sprachen, Konten, Dokumentation und DownloadsDesktop-App-AufbauRust und egui, ohne WebViewRelease- und ZahlungspipelineSignatur, MSI, deb, rpm, AppImage, PrüfsummenVertriebspartnerEmpfehlen und 30 % erhaltenKontaktEntwicklung, Partnerschaft, Investition
Dienste
Remote-DesktopIhren Computer im Browser erreichenIndividuelle InstallationspaketeNur nötige Funktionen, Einstellungen vorab
Kaufen
DE
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Anmelden
Anmelden
TASTEDEV

Von kleinen Werkzeugen zu besserer Entwicklung.

support@tastedev.netTASTEDEV unterstützen
ProdukteProduktübersichtKaufenDokuDownloadsMarktplatzSupport
CommunityProjekteEntwicklungslogsPromptsProbleme mit KI-ToolsShowcase
RichtlinienÜber unsDatenschutzerklärungNutzungsbedingungenAbo-BedingungenRückerstattungCommunity-Richtlinien
KontoAnmeldenRegistrieren
Besucher
Heute
Gestern
Aufrufe gesamt
Firma
GXSOFT
Vertretungsberechtigt
CHOI YOUNG GU
Handelsregisternummer
853-44-00368
Anschrift
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Telefon
+82-10-4404-1523
E-Mail
whitecalvin@tastedev.net
Datenschutzbeauftragter
CHOI YOUNG GU

© 2026 TASTEDEVProduktinformationen basieren auf verifizierten Entwicklungsquellen.Veröffentlicht · wird verbessert

Bäume und Heaps-Dokumentation
Bäume und Heaps
Tree and Heap ConceptsHow It WorksImplementationComplexityPractice ProblemsTrees and Heaps in the Real World
Diskussionen

Bäume und Heaps-Anleitung · 5/6

Practice Problems

Dieses Kapitel ist vorerst nur auf Englisch verfügbar.

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.

Fragen zu diesem Kapitel?
Vorheriges KapitelComplexityNächstes KapitelTrees 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 Kommentare

Top-KommentareNeueste zuerst

Anmelden · Melde dich an, um einen Kommentar zu schreiben.