本文へスキップ
製品デスクトップツールTASTECAD図面の確認TASTEFILESファイル管理TASTEFTPファイル転送TASTESSHリモートワークスペースTASTEZIP圧縮と展開TASTEWINMファイル管理開発ツールTASTECODERust 統合開発環境TASTESTUDIO統合開発・テスト環境TASTEETLデータ統合(ETL)サーバーTASTEREMOTEリモートデスクトップサーバーTASTEGEO空間情報サーバーTASTEMAILメールワークスペース投資TASTESTOCK株式自動売買デスクトップアプリはじめるダウンロードドキュメント購入すべての製品
マーケットプレイス
ニュース
技術ニュース今日の開発ニュース開発ドキュメントプログラミング言語RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWebフロントエンド フレームワークNext.jsReactVue.js · NuxtSvelteKitAngularサーバー フレームワークSpring BootDjangoFastAPIASP.NET CoreNestJS · Expressアプリ・デスクトップ フレームワークTauriFlutterReact NativeElectronアルゴリズムアルゴリズムの基礎主要アルゴリズム発展アルゴリズム実務のアルゴリズム
コミュニティプロジェクト開発ログプロンプトAIツールの問題ショーケースコミュニティガイド
協業技術移転ウェブサイト構築デスクトップアプリ構築リリース・決済パイプライン販売パートナーお問い合わせ
サービスリモートデスクトップインストールパッケージのカスタマイズ
TASTEDEV
製品

デスクトップツール

TASTECAD複雑な図面を、軽やかにひらくTASTEFILES必要なファイルだけを、最速でTASTEFTPファイルが行き交う、いちばん端正な道TASTESSHサーバーとあなたを、より確かにつなぐTASTEZIPより速くまとめ、より安全にひらくTASTEWINM2つの画面で整理する、キーボード中心のファイルマネージャー

開発ツール

TASTECODERust アプリの編集・ビルド・デバッグ・テストまでひとつのウィンドウでTASTESTUDIO編集からリモートテスト、承認した AI 修正までTASTEETL値を見ながら、データを運ぶ

サーバー

TASTEREMOTE自社サーバーで運用するリモートデスクトップTASTEGEOGeoServer 互換の空間情報サーバーを Rust で作り直しますTASTEMAILメールの主導権を、もう一度自分の手に

投資

TASTESTOCKいつ・何を。自分で決めたルールどおりに動く株式自動売買

はじめる

ダウンロード全製品の最新版ドキュメント各製品の使い方購入サブスクリプション・永久ライセンスすべての製品全製品を一覧で
すべての製品
マーケットプレイスニュース
技術

ニュース

今日の開発ニュース言語・フレームワーク・GitHub・AI の公式発表開発ドキュメント言語・フレームワーク・アルゴリズムのガイド

プログラミング言語

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

フレームワーク

Webフロントエンド フレームワークNext.jsReactVue.js · NuxtSvelteKitAngular
サーバー フレームワークSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
アプリ・デスクトップ フレームワークTauriFlutterReact NativeElectron

アルゴリズム

アルゴリズムの基礎計算量解析 · ソート · 探索 · 基本データ構造 · 木構造とヒープ主要アルゴリズムグラフ探索 · 最短経路と最小全域木 · 動的計画法 · 貪欲法 · 分割統治法 · バックトラッキング発展アルゴリズム文字列アルゴリズム · 数学と整数論 · ビット演算 · セグメント木 · Union-Find実務のアルゴリズムコーディング面接対策 · LRUキャッシュ · レート制限 · コンシステントハッシュ法
開発ドキュメントをすべて見る
コミュニティ
プロジェクトビルダーと作品を探す開発ログ決定と試行錯誤プロンプト再利用できる指示AIツールの問題Claude・Codex・Gemini の問題と回避策ショーケース完成した成果コミュニティガイドオープンにつくる方法
協業
技術移転Rust・egui でネイティブアプリを作るウェブサイト構築10言語、アカウント、ドキュメントとダウンロードデスクトップアプリ構築Rust・egui、WebView なしリリース・決済パイプライン署名・MSI・deb・rpm・AppImage・ハッシュ販売パートナー紹介して決済額の30%お問い合わせ構築・提携・投資のご相談
サービス
リモートデスクトップブラウザから自分のパソコンへインストールパッケージのカスタマイズ必要な機能だけ、設定は事前に
購入
JA
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
ログイン
ログイン
TASTEDEV

小さなツールから、より良い開発へ。

support@tastedev.netTASTEDEVを支援
製品製品ラインナップ購入ドキュメントダウンロードマーケットプレイスサポート
コミュニティプロジェクト開発ログプロンプトAIツールの問題ショーケース
ポリシー会社概要プライバシーポリシー利用規約サブスクリプション規約返金ポリシーコミュニティガイドライン
アカウントログイン新規登録
訪問者
今日
昨日
累計閲覧
商号
GXSOFT
代表者
CHOI YOUNG GU
事業者登録番号
853-44-00368
所在地
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
電話
+82-10-4404-1523
メール
whitecalvin@tastedev.net
個人情報保護責任者
CHOI YOUNG GU

© 2026 TASTEDEV製品情報は検証済みの開発ソースに基づいています。リリース・改善中

木構造とヒープ ドキュメント
木構造とヒープ
Tree and Heap ConceptsHow It WorksImplementationComplexityPractice ProblemsTrees and Heaps in the Real World
ディスカッション

木構造とヒープ ガイド · 6/6

Trees and Heaps in the Real World

この章は現在、英語でのみ提供しています。

You will meet trees and heaps far more often as ready-made components than as code you write yourself. This chapter shows where they appear in real systems and which pitfalls catch people when using the standard libraries.

Where they show up

  • Hierarchical data: file system directories, the browser DOM, a compiler's abstract syntax tree (AST), and JSON or XML documents are all trees. Computing folder sizes is a post-order traversal; rendering a page follows a pre-order walk.
  • Database indexes: the default indexes in PostgreSQL, MySQL (InnoDB) and SQLite are B-tree variants. Each node holds hundreds of keys, which keeps the height around 3 or 4 and cuts the number of disk reads. Conceptually, it is a BST widened to many branches.
  • Sorted maps and sets: C++ std::map and std::set (red-black trees in the major implementations) and Java TreeMap and TreeSet (red-black trees) keep keys ordered and answer nearest-value queries such as floorKey or lower_bound in O(log n).
  • Operating system schedulers: the Linux kernel keeps runnable tasks in a red-black tree to pick the next task quickly.
  • Timers and event loops: libuv (used by Node.js) and the Go runtime keep timers in min-heap style structures so the next timer to fire is always at hand.
  • Graph algorithms: Dijkstra's shortest paths, Prim's minimum spanning tree and A* search all pull "the closest candidate so far" from a priority queue.
  • Stream processing: top-K aggregation, external sorting that merges many sorted files, and event-driven simulation all rely on heaps.

Pitfalls with Python heapq

heapq is a set of functions that treat a plain list as a min-heap. The usual way to get a max-heap is to push negated values (Python 3.14 also adds max-heap functions such as heappush_max). When two priorities tie, tuple comparison moves on to the next element, and an incomparable object such as a dict raises TypeError. Putting an increasing counter in the middle fixes this and also keeps equal priorities in insertion order.

import heapq
import itertools

queue, counter = [], itertools.count()


def add(priority, task):
    heapq.heappush(queue, (priority, next(counter), task))


add(2, {"name": "backup"})
add(1, {"name": "deploy"})
add(2, {"name": "report"})       # equal priority, yet dicts are never compared
while queue:
    p, _, task = heapq.heappop(queue)
    print(p, task["name"])       # 1 deploy, 2 backup, 2 report

scores = [5, 1, 9, 3]
max_heap = [-s for s in scores]   # flip the sign to use it as a max-heap
heapq.heapify(max_heap)
print(-max_heap[0], heapq.nlargest(2, scores))  # 9 [9, 5]
この章について質問がありますか?
前の章Practice Problems

A heap does not support changing the priority of, or removing, an arbitrary element. The standard workaround is lazy deletion: push a new entry, mark the old one as stale, and skip stale entries when they are popped. The familiar line if d > dist[u]: continue in Dijkstra's algorithm is exactly this technique.

Pitfalls with C++ priority_queue

std::priority_queue is a max-heap by default. Pass std::greater as the third template argument for a min-heap. top() and pop() are separate calls, and calling either on an empty queue is undefined behaviour, so check empty() first.

#include <functional>
#include <iostream>
#include <queue>
#include <string>
#include <utility>
#include <vector>

int main() {
    std::priority_queue<int> maxq;  // max-heap
    std::priority_queue<int, std::vector<int>, std::greater<int>> minq;  // min-heap
    for (int x : {5, 1, 9, 3}) { maxq.push(x); minq.push(x); }
    std::cout << maxq.top() << ' ' << minq.top() << '\n';  // 9 1

    using Item = std::pair<int, std::string>;  // (distance, name) uses pair ordering
    std::priority_queue<Item, std::vector<Item>, std::greater<Item>> pq;
    pq.push({7, "b"});
    pq.push({3, "a"});
    std::cout << pq.top().second << '\n';  // a
}

Pitfalls with Java PriorityQueue

PriorityQueue is a min-heap by default; a Comparator changes the order. A comparator written as subtraction, (a, b) -> a - b, overflows for large values, so use Integer.compare or Comparator.comparingInt. Iterating with for or printing with toString() shows the internal array order, not sorted order; to see items in order, take them out with poll().

import java.util.Comparator;
import java.util.PriorityQueue;

public class Tasks {
    record Task(String name, int priority) {}

    public static void main(String[] args) {
        PriorityQueue<Integer> max = new PriorityQueue<>(Comparator.reverseOrder());
        max.addAll(java.util.List.of(5, 1, 9, 3));
        System.out.println(max.peek()); // 9

        PriorityQueue<Task> pq = new PriorityQueue<>(Comparator.comparingInt(Task::priority));
        pq.add(new Task("backup", 2));
        pq.add(new Task("deploy", 1));
        while (!pq.isEmpty()) System.out.println(pq.poll().name()); // deploy, backup
    }
}

Summary

Trees form the backbone of file systems, database indexes, sorted maps and schedulers, while heaps are the basic tool for timers, graph algorithms and top-K computations. When using a standard library, keep in mind its default order (min-heap in Python and Java, max-heap in C++), how ties are handled, and lazy deletion for priority changes, and you will avoid most pitfalls.

Further reading

  • Python heapq documentation
  • C++ std::priority_queue (cppreference)
  • Java PriorityQueue API
  • VisuAlgo: Binary Search Tree and AVL Tree
  • VisuAlgo: Binary Heap
  • Wikipedia: Red-black tree
  • Wikipedia: B-tree

コメント 0件

人気のコメント順新しい順

ログイン · ログインするとコメントできます。