Files
hello-algo/ja/codes/cpp/utils/tree_node.hpp
T
Yudong JinandClaude Opus 5.5 b113cb425a Cite the shared TreeNode for the AVL node and the C binary tree node (#2037)
Batch 3b of the runnable-snippets plan. avl_tree_node now cites each
language's shared TreeNode in all 13 languages, and the C tree_node_class
shares the same region. Rust gets an import region; Java, C#, Swift and
Kotlin skip their serialization helpers with an adjacent region.

The shared nodes gain reviewed field comments in C++ and Rust, aligned
comments in Java, Swift and Kotlin, and a spacing fix in JavaScript. The
AVL section adds one sentence saying the shared node class already has
height. Four ru Rust files whose multi-line statements had collapsed into
literal \n now compile again. en, ja, ko and zh-hant are regenerated; ru
is synced by hand.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 05:51:36 +08:00

87 lines
2.3 KiB
C++

/**
* File: tree_node.hpp
* Created Time: 2021-12-19
* Author: krahets ([email protected])
*/
#pragma once
#include <limits.h>
#include <vector>
using namespace std;
// [region]{tree_node}
/* 二分木のノードの構造体 */
struct TreeNode {
int val{}; // ノードの値
int height = 0; // ノードの高さ
TreeNode *parent{};
TreeNode *left{}; // 左の子ノードへのポインタ
TreeNode *right{}; // 右の子ノードへのポインタ
TreeNode() = default;
explicit TreeNode(int x, TreeNode *parent = nullptr) : val(x), parent(parent) {
}
};
// [endregion]{tree_node}
// シリアライズの符号化規則は次を参照:
// https://www.hello-algo.com/ja/chapter_tree/array_representation_of_tree/
// 二分木の配列表現:
// [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15]
// 二分木の連結リスト表現:
// /——— 15
// /——— 7
// /——— 3
// | \——— 6
// | \——— 12
// ——— 1
// \——— 2
// | /——— 9
// \——— 4
// \——— 8
/* リストから二分木へデシリアライズ:再帰 */
TreeNode *vectorToTreeDFS(vector<int> &arr, int i) {
if (i < 0 || i >= arr.size() || arr[i] == INT_MAX) {
return nullptr;
}
TreeNode *root = new TreeNode(arr[i]);
root->left = vectorToTreeDFS(arr, 2 * i + 1);
root->right = vectorToTreeDFS(arr, 2 * i + 2);
return root;
}
/* リストから二分木へデシリアライズ */
TreeNode *vectorToTree(vector<int> arr) {
return vectorToTreeDFS(arr, 0);
}
/* 二分木をシリアライズしてリストにする:再帰 */
void treeToVecorDFS(TreeNode *root, int i, vector<int> &res) {
if (root == nullptr)
return;
while (i >= res.size()) {
res.push_back(INT_MAX);
}
res[i] = root->val;
treeToVecorDFS(root->left, 2 * i + 1, res);
treeToVecorDFS(root->right, 2 * i + 2, res);
}
/* 二分木をシリアライズしてリストにする */
vector<int> treeToVecor(TreeNode *root) {
vector<int> res;
treeToVecorDFS(root, 0, res);
return res;
}
/* 二分木のメモリを解放する */
void freeMemoryTree(TreeNode *root) {
if (root == nullptr)
return;
freeMemoryTree(root->left);
freeMemoryTree(root->right);
delete root;
}