mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-02 03:05:24 +08:00
* feat(ko): add the complete Korean online edition * Use UTF-8 for Python CI output on Windows * Remove print-book promotion from the Korean site * fix(ko): preserve emphasis before Korean particles
64 lines
2.0 KiB
Zig
64 lines
2.0 KiB
Zig
// File: TreeNode.zig
|
|
// Created Time: 2023-01-07
|
|
// Author: codingonion ([email protected]), CreatorMetaSky ([email protected])
|
|
|
|
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, // 오른쪽 자식 노드 포인터
|
|
|
|
// 지정한 값으로 트리 노드를 초기화한다
|
|
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;
|
|
}
|