From e8f1a676b2829f1dd4ff87efab42c0d9125b3519 Mon Sep 17 00:00:00 2001 From: sjinzh <99076655+sjinzh@users.noreply.github.com> Date: Sat, 14 Jan 2023 08:47:50 +0800 Subject: [PATCH] add zig codes for Section 'Binary Tree' --- codes/zig/build.zig | 14 ++++++++ codes/zig/chapter_tree/binary_tree.zig | 44 ++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 codes/zig/chapter_tree/binary_tree.zig diff --git a/codes/zig/build.zig b/codes/zig/build.zig index 5a97289d2..f66c559df 100644 --- a/codes/zig/build.zig +++ b/codes/zig/build.zig @@ -174,6 +174,20 @@ pub fn build(b: *std.build.Builder) void { const run_step_hash_map= b.step("run_hash_map", "Run hash_map"); run_step_hash_map.dependOn(&run_cmd_hash_map.step); + // Section: "Binary Tree" + // Source File: "chapter_tree/binary_tree.zig" + // Run Command: zig build run_binary_tree + const exe_binary_tree = b.addExecutable("hash_map", "chapter_tree/binary_tree.zig"); + exe_binary_tree.addPackagePath("include", "include/include.zig"); + exe_binary_tree.setTarget(target); + exe_binary_tree.setBuildMode(mode); + exe_binary_tree.install(); + const run_cmd_binary_tree = exe_binary_tree.run(); + run_cmd_binary_tree.step.dependOn(b.getInstallStep()); + if (b.args) |args| run_cmd_binary_tree.addArgs(args); + const run_step_binary_tree= b.step("run_binary_tree", "Run binary_tree"); + run_step_binary_tree.dependOn(&run_cmd_binary_tree.step); + // Section: "Heap" // Source File: "chapter_heap/heap.zig" // Run Command: zig build run_heap diff --git a/codes/zig/chapter_tree/binary_tree.zig b/codes/zig/chapter_tree/binary_tree.zig new file mode 100644 index 000000000..22d47eea8 --- /dev/null +++ b/codes/zig/chapter_tree/binary_tree.zig @@ -0,0 +1,44 @@ +// File: binary_tree.zig +// Created Time: 2023-01-14 +// Author: sjinzh (sjinzh@gmail.com) + +const std = @import("std"); +const inc = @import("include"); + +// Driver Code +pub fn main() !void { + // 查看本地CPU架构和操作系统信息 + var native_target_info = try std.zig.system.NativeTargetInfo.detect(std.zig.CrossTarget{}); + std.debug.print("Native Info: CPU Arch = {}, OS = {}\n", .{native_target_info.target.cpu.arch, native_target_info.target.os.tag}); + + // 初始化二叉树 + // 初始化结点 + var n1 = inc.TreeNode(i32){ .val = 1 }; + var n2 = inc.TreeNode(i32){ .val = 2 }; + var n3 = inc.TreeNode(i32){ .val = 3 }; + var n4 = inc.TreeNode(i32){ .val = 4 }; + var n5 = inc.TreeNode(i32){ .val = 5 }; + // 构建引用指向(即指针) + n1.left = &n2; + n1.right = &n3; + n2.left = &n4; + n2.right = &n5; + std.debug.print("初始化二叉树\n", .{}); + try inc.PrintUtil.printTree(&n1, null, false); + + // 插入与删除结点 + var p = inc.TreeNode(i32){ .val = 0 }; + // 在 n1 -> n2 中间插入结点 P + n1.left = &p; + p.left = &n2; + std.debug.print("插入结点 P 后\n", .{}); + try inc.PrintUtil.printTree(&n1, null, false); + // 删除结点 + n1.left = &n2; + std.debug.print("删除结点 P 后\n", .{}); + try inc.PrintUtil.printTree(&n1, null, false); + + const getchar = try std.io.getStdIn().reader().readByte(); + _ = getchar; +} +