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 · 1/6

Tree and Heap Concepts

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

Arrays and linked lists put data in a single line. Hierarchical data, such as folders inside folders, an org chart or the tags of an HTML page, does not fit a line well. The structure built for it is the tree. Restrict a tree one way and you get the binary search tree, which finds keys in sorted data quickly. Restrict it another way and you get the heap, which hands you the smallest (or largest) value quickly. This chapter sets up the vocabulary and intuition for all three.

What a tree is

A tree is made of nodes joined by edges, with these properties:

  • There is exactly one root at the top.
  • Every node except the root has exactly one parent.
  • There are no cycles, so there is exactly one path from the root to any node.
  • A tree with n nodes always has n - 1 edges.

In graph terms, a rooted tree is a connected acyclic graph with one node chosen as the root.

Vocabulary

TermMeaning
Parent, childNodes directly connected by an edge, above and below
SiblingsNodes that share a parent
LeafA node with no children
Internal nodeA node with at least one child
DepthNumber of edges from the root to the node (the root has depth 0)
HeightNumber of edges from the node down to its farthest leaf (a leaf has height 0)
SubtreeA node together with all of its descendants
DegreeNumber of children of a node

The height of a tree is the height of its root. A single-node tree has height 0, and the empty tree is conventionally -1. Some textbooks count height in nodes instead of edges, so check the definition before solving a problem.

Binary trees

A binary tree is a tree where every node has at most two children, called left and right. Common shapes:

  • Full: every node has 0 or 2 children.
  • Perfect: all leaves are at the same depth and every internal node has two children. A perfect tree of height h has 2^(h+1) - 1 nodes.
  • Complete: every level is full except possibly the last, which is filled from the left. Heaps have exactly this shape.
  • Degenerate: every node has a single child, so the tree is really a linked list.

In Python a node is a small class.

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


def height(node):
    if node is None:
        return -1
    return 1 + max(height(node.left), height(node.right))


def size(node):
    if node is None:
        return 0
    return 1 + size(node.left) + size(node.right)


#       8
#      / \
#     3   10
#    / \    \
#   1   6    14
root = Node(8, Node(3, Node(1), Node(6)), Node(10, None, Node(14)))
print(height(root), size(root))  # 2 6
Dúvidas sobre este capítulo?
Próximo capítuloHow It Works

Binary search trees (BST)

A binary search tree is a binary tree where, at every node, all keys in the left subtree are smaller and all keys in the right subtree are larger. Starting at the root, each comparison discards an entire subtree, which is the same effect as binary search on a sorted array. An in-order traversal (left, node, right) visits the keys in ascending order.

The rule applies to whole subtrees, not just to the immediate children. To check that a tree is a BST, pass the allowed range down as you recurse.

def is_bst(node, low=float("-inf"), high=float("inf")):
    if node is None:
        return True
    if not (low < node.key < high):
        return False
    return is_bst(node.left, low, node.key) and is_bst(node.right, node.key, high)


print(is_bst(root))  # True

Why balance matters

Search, insert and delete in a BST cost time proportional to the height h. With well-spread keys, h is about log2 n, but inserting keys in sorted order (1, 2, 3, ...) produces a degenerate tree with h = n - 1. Self-balancing trees fix this by restoring their shape with rotations on every insert and delete. The two best known are the AVL tree, which keeps the height difference between the left and right subtrees of every node at most 1, and the red-black tree, which colours nodes red or black so that no path is more than twice as long as any other. This guide explains the idea only; in practice you use the implementation your language provides.

Heaps and priority queues

A binary heap is a binary tree with two properties. First, its shape is a complete binary tree. Second, in a min-heap every parent is less than or equal to its children (a max-heap is the reverse). The root therefore always holds the minimum, but siblings and separate subtrees are in no particular order. A heap is not sorted like a BST; it only guarantees where the smallest element is.

Because a complete binary tree has no gaps, it can be stored in a plain array in level order, with no pointers.

def parent(i):
    return (i - 1) // 2


def left(i):
    return 2 * i + 1


def right(i):
    return 2 * i + 2


heap = [1, 3, 2, 7, 4, 5]  # a min-heap
for i in range(1, len(heap)):
    assert heap[parent(i)] <= heap[i]
print(heap[0], left(1), right(1))  # 1 3 4

The heap is the most common way to implement a priority queue, an abstract data type that supports "insert a value" and "remove the highest-priority value". With a heap, both operations take O(log n).

Which one to use

  • Hierarchical data: a general tree (file systems, the DOM, syntax trees).
  • Lookups that also need sorted order, range queries or previous/next values: a balanced BST.
  • Repeatedly taking the smallest (or largest) item: a heap or priority queue.
  • Lookups by key only: a hash table is usually faster.

Summary

A tree is a hierarchy in which every node is reached from the root by exactly one path. A binary search tree keeps smaller keys on the left and larger keys on the right, and its performance depends on keeping the height low. A heap only maintains a complete shape and parent-child order, which lets it live in an array and implement a priority queue efficiently.

0 comentários

Principais comentáriosMais recentes primeiro

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