2023-01-14 08:47:50 +08:00
|
|
|
// 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 {
|
|
|
|
// 初始化二叉树
|
2023-04-09 04:32:17 +08:00
|
|
|
// 初始化节点
|
2023-01-14 08:47:50 +08:00
|
|
|
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);
|
|
|
|
|
2023-04-09 04:32:17 +08:00
|
|
|
// 插入与删除节点
|
2023-01-14 08:47:50 +08:00
|
|
|
var p = inc.TreeNode(i32){ .val = 0 };
|
2023-04-09 04:32:17 +08:00
|
|
|
// 在 n1 -> n2 中间插入节点 P
|
2023-01-14 08:47:50 +08:00
|
|
|
n1.left = &p;
|
|
|
|
p.left = &n2;
|
2023-04-09 04:32:17 +08:00
|
|
|
std.debug.print("插入节点 P 后\n", .{});
|
2023-01-14 08:47:50 +08:00
|
|
|
try inc.PrintUtil.printTree(&n1, null, false);
|
2023-04-09 04:32:17 +08:00
|
|
|
// 删除节点
|
2023-01-14 08:47:50 +08:00
|
|
|
n1.left = &n2;
|
2023-04-09 04:32:17 +08:00
|
|
|
std.debug.print("删除节点 P 后\n", .{});
|
2023-01-14 08:47:50 +08:00
|
|
|
try inc.PrintUtil.printTree(&n1, null, false);
|
|
|
|
|
2023-02-06 01:14:03 +08:00
|
|
|
_ = try std.io.getStdIn().reader().readByte();
|
2023-01-14 08:47:50 +08:00
|
|
|
}
|
|
|
|
|