2023-01-09 19:31:45 +08:00
|
|
|
// File: TreeNode.zig
|
|
|
|
// Created Time: 2023-01-07
|
|
|
|
// Author: sjinzh (sjinzh@gmail.com)
|
|
|
|
|
|
|
|
const std = @import("std");
|
|
|
|
|
|
|
|
// Definition for a binary tree node
|
2023-01-10 17:19:21 +08:00
|
|
|
// 编译期泛型
|
2023-01-09 19:31:45 +08:00
|
|
|
pub fn TreeNode(comptime T: type) type {
|
|
|
|
return struct {
|
|
|
|
const Self = @This();
|
|
|
|
|
|
|
|
val: T = 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;
|
2023-01-13 23:40:37 +08:00
|
|
|
self.left = null;
|
|
|
|
self.right = null;
|
2023-01-09 19:31:45 +08:00
|
|
|
}
|
|
|
|
};
|
2023-01-14 08:11:54 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Generate a binary tree with an array
|
|
|
|
pub fn arrToTree(comptime T: type, mem_allocator: std.mem.Allocator, list: []T) !?*TreeNode(T) {
|
|
|
|
if (list.len == 0) return null;
|
|
|
|
var root = try mem_allocator.create(TreeNode(T));
|
|
|
|
root.init(list[0]);
|
2023-01-14 22:28:23 +08:00
|
|
|
var que = std.ArrayList(*TreeNode(T)).init(std.heap.page_allocator);
|
|
|
|
try que.append(root);
|
2023-01-14 08:11:54 +08:00
|
|
|
var index: usize = 0;
|
2023-01-14 22:28:23 +08:00
|
|
|
while (que.items.len > 0) {
|
|
|
|
var node = que.orderedRemove(0);
|
2023-01-14 08:11:54 +08:00
|
|
|
index += 1;
|
|
|
|
if (index >= list.len) break;
|
|
|
|
if (index < list.len) {
|
|
|
|
var tmp = try mem_allocator.create(TreeNode(T));
|
|
|
|
tmp.init(list[index]);
|
2023-01-14 22:28:23 +08:00
|
|
|
node.left = tmp;
|
|
|
|
try que.append(node.left.?);
|
2023-01-14 08:11:54 +08:00
|
|
|
}
|
|
|
|
index += 1;
|
|
|
|
if (index >= list.len) break;
|
|
|
|
if (index < list.len) {
|
|
|
|
var tmp = try mem_allocator.create(TreeNode(T));
|
|
|
|
tmp.init(list[index]);
|
2023-01-14 22:28:23 +08:00
|
|
|
node.right = tmp;
|
|
|
|
try que.append(node.right.?);
|
2023-01-14 08:11:54 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return root;
|
2023-01-09 19:31:45 +08:00
|
|
|
}
|