Pular para o conteúdo principal
ProdutosFerramentas de desktopTASTECADVisualização de desenhosTASTEFILESGerenciamento de arquivosTASTEFTPTransferência de arquivosTASTESSHEspaço de trabalho remotoTASTEZIPCompactação e extraçãoTASTEWINMGerenciamento de arquivosFerramentas para desenvolvedoresTASTECODEAmbiente de desenvolvimento integrado para RustTASTESTUDIOAmbiente integrado de desenvolvimento e testesTASTEETLIntegração de dados (ETL)ServidoresTASTEREMOTEServidor de área de trabalho remotaTASTEGEOServidor geoespacialTASTEMAILEspaço de trabalho de e-mailInvestimentosTASTESTOCKAplicativo desktop de negociação automática de açõesComeçarDownloadsDocumentaçãoComprarTodos os produtos
Marketplace
Notícias
TecnologiaNotíciasNotícias de desenvolvimento de hojeDocumentaçãoLinguagens de programaçãoRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks de front-end webNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks de apps e desktopTauriFlutterReact NativeElectronAlgoritmosFundamentos de algoritmosAlgoritmos essenciaisAlgoritmos avançadosAlgoritmos práticos
ComunidadeProjetosRegistros de desenvolvimentoPromptsProblemas de ferramentas de IAVitrineGuia da comunidade
ColaboreTransferência técnicaConstrução de siteConstrução de app de desktopPipeline de lançamento e pagamentoParceiro de vendasContato
ServiçosÁrea de trabalho remotaPacotes de instalação sob medida
TASTEDEV
Produtos

Ferramentas de desktop

TASTECADDesenhos complexos, abertos com levezaTASTEFILESSó os arquivos de que você precisa, o mais rápido possívelTASTEFTPO caminho mais organizado para seus arquivosTASTESSHEntre você e o servidor, uma conexão mais sólidaTASTEZIPCompacte mais rápido, extraia com mais segurançaTASTEWINMUm gerenciador de arquivos de dois painéis feito para o teclado

Ferramentas para desenvolvedores

TASTECODEEdite, compile, depure e teste apps Rust em uma única janelaTASTESTUDIODa edição aos testes remotos e às correções com IA aprovadasTASTEETLMova dados de olho nos valores

Servidores

TASTEREMOTEUma área de trabalho remota rodando no seu próprio servidorTASTEGEOUm servidor geoespacial compatível com o GeoServer, reconstruído em RustTASTEMAILRetome o controle do seu e-mail

Investimentos

TASTESTOCKNegociação automática de ações pelas regras que você define: quando e o quê

Começar

DownloadsVersões mais recentes de cada produtoDocsComo usar cada produtoComprarAssinaturas e licenças perpétuasTodos os produtosTodos os produtos de relance
Todos os produtos
MarketplaceNotícias
Tecnologia

Notícias

Notícias de desenvolvimento de hojeAnúncios oficiais de linguagens, frameworks, GitHub e IADocumentaçãoGuias de linguagens, frameworks e algoritmos

Linguagens de programação

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks de front-end webNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks de apps e desktopTauriFlutterReact NativeElectron

Algoritmos

Fundamentos de algoritmosAnálise de complexidade · Ordenação · Busca · Estruturas de dados básicas · Árvores e heapsAlgoritmos essenciaisBusca em grafos · Caminho mínimo e árvore geradora mínima · Programação dinâmica · Algoritmos gulosos · Divisão e conquista · BacktrackingAlgoritmos avançadosAlgoritmos de strings · Matemática e teoria dos números · Manipulação de bits · Árvores de segmentos · Union-FindAlgoritmos práticosEstratégia para entrevistas de código · Cache LRU · Limitação de taxa · Hashing consistente
Toda a documentação de desenvolvimento
Comunidade
ProjetosDescubra criadores e trabalhosRegistros de desenvolvimentoDecisões e aprendizadosPromptsInstruções reutilizáveisProblemas de ferramentas de IAProblemas e contornos de Claude, Codex, GeminiVitrineResultados concluídosGuia da comunidadeComo construímos em aberto
Colabore
Transferência técnicaApps nativos em Rust e eguiConstrução de site10 idiomas, contas, documentação e downloadsConstrução de app de desktopRust e egui, sem WebViewPipeline de lançamento e pagamentoAssinatura, MSI, deb, rpm, AppImage, hashesParceiro de vendasRecomende e ganhe 30%ContatoDesenvolvimento, parcerias e investimento
Serviços
Área de trabalho remotaAcesse seu computador pelo navegadorPacotes de instalação sob medidaSó o necessário, configurações pré-carregadas
Comprar
PT
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Entrar
Entrar
TASTEDEV

De pequenas ferramentas a um desenvolvimento melhor.

support@tastedev.netApoiar TASTEDEV
ProdutosLinha de produtosComprarDocsDownloadsMarketplaceSuporte
ComunidadeProjetosRegistros de desenvolvimentoPromptsProblemas de ferramentas de IAVitrine
PolíticasSobre nósPolítica de privacidadeTermos de usoTermos de assinaturaReembolsoDiretrizes da comunidade
ContaEntrarCriar conta
Visitantes
Hoje
Ontem
Visualizações totais
Empresa
GXSOFT
Representante
CHOI YOUNG GU
Número de registro comercial
853-44-00368
Endereço
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Telefone
+82-10-4404-1523
E-mail
whitecalvin@tastedev.net
Responsável pela privacidade
CHOI YOUNG GU

© 2026 TASTEDEVAs informações dos produtos se baseiam em fontes de desenvolvimento verificadas.Lançado · em melhoria

Documentação de Árvores e heaps
Árvores e heaps
Tree and Heap ConceptsHow It WorksImplementationComplexityPractice ProblemsTrees and Heaps in the Real World
Discussões

Guia de Árvores e heaps · 5/6

Practice Problems

Por enquanto, este capítulo está disponível apenas em inglês.

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.

Dúvidas sobre este capítulo?
Capítulo anteriorComplexityPróximo capítuloTrees 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 comentários

Principais comentáriosMais recentes primeiro

Fazer login · Faça login para deixar um comentário.