Aller au contenu principal
ProduitsOutils de bureauTASTECADConsultation de plansTASTEFILESGestion de fichiersTASTEFTPTransfert de fichiersTASTESSHEspace de travail à distanceTASTEZIPCompression et extractionTASTEWINMGestion de fichiersOutils pour développeursTASTECODEEnvironnement de développement intégré pour RustTASTESTUDIOEnvironnement intégré de développement et de testTASTEETLIntégration de données (ETL)ServeursTASTEREMOTEServeur de bureau à distanceTASTEGEOServeur géospatialTASTEMAILEspace de travail e-mailInvestissementTASTESTOCKApplication de bureau de trading automatique d'actionsCommencerTéléchargementsDocumentationAcheterTous les produits
Marketplace
Actualités
TechActualitésL’actu dev du jourDocs développeursLangages de programmationRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks front-end webNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks serveurSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks d'applications et de bureauTauriFlutterReact NativeElectronAlgorithmesBases des algorithmesAlgorithmes essentielsAlgorithmes avancésAlgorithmes pratiques
CommunautéProjetsJournaux de développementPromptsProblèmes d’outils d’IAVitrineGuide de la communauté
CollaborerTransfert techniqueRéalisation de site webRéalisation d'application de bureauChaîne de publication et de paiementPartenaire commercialContact
ServicesBureau à distancePaquets d'installation sur mesure
TASTEDEV
Produits

Outils de bureau

TASTECADDes plans complexes, ouverts en toute légèretéTASTEFILESSeulement les fichiers utiles, au plus viteTASTEFTPLe chemin le plus net pour vos fichiersTASTESSHEntre vos serveurs et vous, un lien plus solideTASTEZIPCompresser plus vite, extraire en toute sécuritéTASTEWINMUn gestionnaire de fichiers à deux volets, pensé pour le clavier

Outils pour développeurs

TASTECODEModifier, compiler, déboguer et tester vos apps Rust dans une seule fenêtreTASTESTUDIODe l’édition aux tests à distance et aux corrections IA approuvéesTASTEETLDéplacer les données, les valeurs sous les yeux

Serveurs

TASTEREMOTEUn bureau à distance hébergé sur votre propre serveurTASTEGEOUn serveur géospatial compatible GeoServer, reconstruit en RustTASTEMAILReprenez la maîtrise de vos e-mails

Investissement

TASTESTOCKDu trading automatique d'actions selon vos règles : quand, et quoi

Commencer

TéléchargementsDernières versions de chaque produitDocsUtiliser chaque produitAcheterAbonnements et licences perpétuellesTous les produitsTous les produits en un coup d’œil
Tous les produits
MarketplaceActualités
Tech

Actualités

L’actu dev du jourAnnonces officielles : langages, frameworks, GitHub et IADocs développeursGuides des langages, frameworks et algorithmes

Langages de programmation

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks front-end webNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks serveurSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks d'applications et de bureauTauriFlutterReact NativeElectron

Algorithmes

Bases des algorithmesAnalyse de complexité · Tri · Recherche · Structures de données de base · Arbres et tasAlgorithmes essentielsParcours de graphe · Plus courts chemins et arbres couvrants · Programmation dynamique · Algorithmes gloutons · Diviser pour régner · Backtracking (retour sur trace)Algorithmes avancésAlgorithmes sur les chaînes · Mathématiques et théorie des nombres · Manipulation de bits · Arbres de segments · Union-FindAlgorithmes pratiquesStratégie pour les entretiens de codage · Cache LRU · Limitation de débit · Hachage cohérent
Toute la documentation de développement
Communauté
ProjetsDécouvrir les créateurs et leurs travauxJournaux de développementDécisions et enseignementsPromptsInstructions réutilisablesProblèmes d’outils d’IAProblèmes et contournements de Claude, Codex, GeminiVitrineRéalisations terminéesGuide de la communautéConstruire en toute transparence
Collaborer
Transfert techniqueApplications natives en Rust et eguiRéalisation de site web10 langues, comptes, documentation et téléchargementsRéalisation d'application de bureauRust et egui, sans WebViewChaîne de publication et de paiementSignature, MSI, deb, rpm, AppImage, empreintesPartenaire commercialRecommandez-nous, touchez 30 %ContactDéveloppement, partenariats, investissement
Services
Bureau à distanceAccédez à votre ordinateur depuis le navigateurPaquets d'installation sur mesureSeulement l'utile, réglages préchargés
Acheter
FR
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Se connecter
Se connecter
TASTEDEV

Des petits outils à un meilleur développement.

support@tastedev.netSoutenir TASTEDEV
ProduitsGamme de produitsAcheterDocsTéléchargementsMarketplaceAssistance
CommunautéProjetsJournaux de développementPromptsProblèmes d’outils d’IAVitrine
RèglesÀ proposPolitique de confidentialitéConditions d'utilisationConditions d’abonnementRemboursementRègles de la communauté
CompteSe connecterS'inscrire
Visiteurs
Aujourd’hui
Hier
Vues au total
Société
GXSOFT
Représentant
CHOI YOUNG GU
Numéro d’enregistrement
853-44-00368
Adresse
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Téléphone
+82-10-4404-1523
E-mail
whitecalvin@tastedev.net
Responsable de la confidentialité
CHOI YOUNG GU

© 2026 TASTEDEVLes informations produit s'appuient sur des sources de développement vérifiées.Publié · en amélioration

Documentation Arbres et tas
Arbres et tas
Tree and Heap ConceptsHow It WorksImplementationComplexityPractice ProblemsTrees and Heaps in the Real World
Discussions

Guide Arbres et tas · 1/6

Tree and Heap Concepts

Ce chapitre n'est disponible qu'en anglais pour le moment.

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
Des questions sur ce chapitre ?
Chapitre suivantHow 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 commentaire

Meilleurs commentairesPlus récents d'abord

Se connecter · Connectez-vous pour laisser un commentaire.