mirror of
https://github.com/krahets/hello-algo.git
synced 2026-07-11 06:56:06 +00:00
Re-translate the Japanese version (#1871)
* Retranslate Japanese docs with GPT-5.4 * Retranslate Japanese code with GPT-5.4
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
// File: TreeNode.zig
|
||||
// Created Time: 2023-01-07
|
||||
// Author: codingonion (coderonion@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// 二分木ノード
|
||||
pub fn TreeNode(comptime T: type) type {
|
||||
return struct {
|
||||
const Self = @This();
|
||||
|
||||
val: T = undefined, // ノード値
|
||||
height: i32 = undefined, // ノードの高さ
|
||||
left: ?*Self = null, // 左の子ノードへのポインタ
|
||||
right: ?*Self = null, // 右の子ノードへのポインタ
|
||||
|
||||
// Initialize a tree node with specific value
|
||||
pub fn init(self: *Self, x: i32) void {
|
||||
self.val = x;
|
||||
self.height = 0;
|
||||
self.left = null;
|
||||
self.right = null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// 配列をデシリアライズして二分木に変換する
|
||||
pub fn arrToTree(comptime T: type, allocator: std.mem.Allocator, arr: []T) !?*TreeNode(T) {
|
||||
if (arr.len == 0) return null;
|
||||
var root = try allocator.create(TreeNode(T));
|
||||
root.init(arr[0]);
|
||||
const L = std.TailQueue(*TreeNode(T));
|
||||
var que = L{};
|
||||
var root_node = try allocator.create(L.Node);
|
||||
root_node.data = root;
|
||||
que.append(root_node);
|
||||
var index: usize = 0;
|
||||
while (que.len > 0) {
|
||||
const que_node = que.popFirst().?;
|
||||
var node = que_node.data;
|
||||
index += 1;
|
||||
if (index >= arr.len) break;
|
||||
if (index < arr.len) {
|
||||
var tmp = try allocator.create(TreeNode(T));
|
||||
tmp.init(arr[index]);
|
||||
node.left = tmp;
|
||||
var tmp_node = try allocator.create(L.Node);
|
||||
tmp_node.data = node.left.?;
|
||||
que.append(tmp_node);
|
||||
}
|
||||
index += 1;
|
||||
if (index >= arr.len) break;
|
||||
if (index < arr.len) {
|
||||
var tmp = try allocator.create(TreeNode(T));
|
||||
tmp.init(arr[index]);
|
||||
node.right = tmp;
|
||||
var tmp_node = try allocator.create(L.Node);
|
||||
tmp_node.data = node.right.?;
|
||||
que.append(tmp_node);
|
||||
}
|
||||
}
|
||||
return root;
|
||||
}
|
||||
Reference in New Issue
Block a user