add zig codes for Section Binary Tree, Binary Search Tree and AVL Tree (#293)

* add zig codes for Section 'Binary Tree'

* add zig codes for Section 'Binary Tree'

* add zig codes for Section 'Binary Tree'

* add zig codes for Section 'Binary Tree'

* add zig codes for Section 'Binary Tree' and 'Binary Search Tree'

* update zig codes for Section 'Binary Tree' and 'Binary Search Tree'

* update zig codes for Section 'Binary Tree', 'Binary Search Tree' and 'AVL Tree'
pull/298/head
sjinzh 2 years ago committed by GitHub
parent 3858048d0f
commit b951eb0cfc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -281,6 +281,47 @@ pub fn build(b: *std.build.Builder) void {
const run_step_binary_tree_bfs = b.step("run_binary_tree_bfs", "Run binary_tree_bfs");
run_step_binary_tree_bfs.dependOn(&run_cmd_binary_tree_bfs.step);
// Source File: "chapter_tree/binary_tree_dfs.zig"
// Run Command: zig build run_binary_tree_dfs
const exe_binary_tree_dfs = b.addExecutable("binary_tree_dfs", "chapter_tree/binary_tree_dfs.zig");
exe_binary_tree_dfs.addPackagePath("include", "include/include.zig");
exe_binary_tree_dfs.setTarget(target);
exe_binary_tree_dfs.setBuildMode(mode);
exe_binary_tree_dfs.install();
const run_cmd_binary_tree_dfs = exe_binary_tree_dfs.run();
run_cmd_binary_tree_dfs.step.dependOn(b.getInstallStep());
if (b.args) |args| run_cmd_binary_tree_dfs.addArgs(args);
const run_step_binary_tree_dfs = b.step("run_binary_tree_dfs", "Run binary_tree_dfs");
run_step_binary_tree_dfs.dependOn(&run_cmd_binary_tree_dfs.step);
// Section: "Binary Search Tree"
// Source File: "chapter_tree/binary_search_tree.zig"
// Run Command: zig build run_binary_search_tree
const exe_binary_search_tree = b.addExecutable("binary_search_tree", "chapter_tree/binary_search_tree.zig");
exe_binary_search_tree.addPackagePath("include", "include/include.zig");
exe_binary_search_tree.setTarget(target);
exe_binary_search_tree.setBuildMode(mode);
exe_binary_search_tree.install();
const run_cmd_binary_search_tree = exe_binary_search_tree.run();
run_cmd_binary_search_tree.step.dependOn(b.getInstallStep());
if (b.args) |args| run_cmd_binary_search_tree.addArgs(args);
const run_step_binary_search_tree = b.step("run_binary_search_tree", "Run binary_search_tree");
run_step_binary_search_tree.dependOn(&run_cmd_binary_search_tree.step);
// Section: "AVL Tree"
// Source File: "chapter_tree/avl_tree.zig"
// Run Command: zig build run_avl_tree
const exe_avl_tree = b.addExecutable("avl_tree", "chapter_tree/avl_tree.zig");
exe_avl_tree.addPackagePath("include", "include/include.zig");
exe_avl_tree.setTarget(target);
exe_avl_tree.setBuildMode(mode);
exe_avl_tree.install();
const run_cmd_avl_tree = exe_avl_tree.run();
run_cmd_avl_tree.step.dependOn(b.getInstallStep());
if (b.args) |args| run_cmd_avl_tree.addArgs(args);
const run_step_avl_tree = b.step("run_avl_tree", "Run avl_tree");
run_step_avl_tree.dependOn(&run_cmd_avl_tree.step);
// Section: "Heap"
// Source File: "chapter_heap/heap.zig"
// Run Command: zig build run_heap

@ -0,0 +1,260 @@
// File: avl_tree.zig
// Created Time: 2023-01-15
// Author: sjinzh (sjinzh@gmail.com)
const std = @import("std");
const inc = @import("include");
//
pub fn AVLTree(comptime T: type) type {
return struct {
const Self = @This();
root: ?*inc.TreeNode(T) = null, //
mem_arena: ?std.heap.ArenaAllocator = null,
mem_allocator: std.mem.Allocator = undefined, //
//
pub fn init(self: *Self, allocator: std.mem.Allocator) void {
if (self.mem_arena == null) {
self.mem_arena = std.heap.ArenaAllocator.init(allocator);
self.mem_allocator = self.mem_arena.?.allocator();
}
}
//
pub fn deinit(self: *Self) void {
if (self.mem_arena == null) return;
self.mem_arena.?.deinit();
}
//
fn height(self: *Self, node: ?*inc.TreeNode(T)) i32 {
_ = self;
// -1 0
return if (node == null) -1 else node.?.height;
}
//
fn updateHeight(self: *Self, node: ?*inc.TreeNode(T)) void {
// + 1
node.?.height = std.math.max(self.height(node.?.left), self.height(node.?.right)) + 1;
}
//
fn balanceFactor(self: *Self, node: ?*inc.TreeNode(T)) i32 {
// 0
if (node == null) return 0;
// = -
return self.height(node.?.left) - self.height(node.?.right);
}
//
fn rightRotate(self: *Self, node: ?*inc.TreeNode(T)) ?*inc.TreeNode(T) {
var child = node.?.left;
var grandChild = child.?.right;
// child node
child.?.right = node;
node.?.left = grandChild;
//
self.updateHeight(node);
self.updateHeight(child);
//
return child;
}
//
fn leftRotate(self: *Self, node: ?*inc.TreeNode(T)) ?*inc.TreeNode(T) {
var child = node.?.right;
var grandChild = child.?.left;
// child node
child.?.left = node;
node.?.right = grandChild;
//
self.updateHeight(node);
self.updateHeight(child);
//
return child;
}
// 使
fn rotate(self: *Self, node: ?*inc.TreeNode(T)) ?*inc.TreeNode(T) {
// node
var balance_factor = self.balanceFactor(node);
//
if (balance_factor > 1) {
if (self.balanceFactor(node.?.left) >= 0) {
//
return self.rightRotate(node);
} else {
//
node.?.left = self.leftRotate(node.?.left);
return self.rightRotate(node);
}
}
//
if (balance_factor < -1) {
if (self.balanceFactor(node.?.right) <= 0) {
//
return self.leftRotate(node);
} else {
//
node.?.right = self.rightRotate(node.?.right);
return self.leftRotate(node);
}
}
//
return node;
}
//
fn insert(self: *Self, val: T) !?*inc.TreeNode(T) {
self.root = try self.insertHelper(self.root, val);
return self.root;
}
//
fn insertHelper(self: *Self, node_: ?*inc.TreeNode(T), val: T) !?*inc.TreeNode(T) {
var node = node_;
if (node == null) {
var tmp_node = try self.mem_allocator.create(inc.TreeNode(T));
tmp_node.init(val);
return tmp_node;
}
// 1.
if (val < node.?.val) {
node.?.left = try self.insertHelper(node.?.left, val);
} else if (val > node.?.val) {
node.?.right = try self.insertHelper(node.?.right, val);
} else {
return node; //
}
self.updateHeight(node); //
// 2. 使
node = self.rotate(node);
//
return node;
}
//
fn remove(self: *Self, val: T) ?*inc.TreeNode(T) {
self.root = self.removeHelper(self.root, val);
return self.root;
}
//
fn removeHelper(self: *Self, node_: ?*inc.TreeNode(T), val: T) ?*inc.TreeNode(T) {
var node = node_;
if (node == null) return null;
// 1.
if (val < node.?.val) {
node.?.left = self.removeHelper(node.?.left, val);
} else if (val > node.?.val) {
node.?.right = self.removeHelper(node.?.right, val);
} else {
if (node.?.left == null or node.?.right == null) {
var child = if (node.?.left != null) node.?.left else node.?.right;
// = 0 node
if (child == null) {
return null;
// = 1 node
} else {
node = child;
}
} else {
// = 2
var temp = self.getInOrderNext(node.?.right);
node.?.right = self.removeHelper(node.?.right, temp.?.val);
node.?.val = temp.?.val;
}
}
self.updateHeight(node); //
// 2. 使
node = self.rotate(node);
//
return node;
}
// root
fn getInOrderNext(self: *Self, node_: ?*inc.TreeNode(T)) ?*inc.TreeNode(T) {
_ = self;
var node = node_;
if (node == null) return node;
// 访
while (node.?.left != null) {
node = node.?.left;
}
return node;
}
//
fn search(self: *Self, val: T) ?*inc.TreeNode(T) {
var cur = self.root;
//
while (cur != null) {
// cur
if (cur.?.val < val) {
cur = cur.?.right;
// cur
} else if (cur.?.val > val) {
cur = cur.?.left;
//
} else {
break;
}
}
//
return cur;
}
};
}
pub fn testInsert(comptime T: type, tree_: *AVLTree(T), val: T) !void {
var tree = tree_;
_ = try tree.insert(val);
std.debug.print("\n插入结点 {} 后AVL 树为\n", .{val});
try inc.PrintUtil.printTree(tree.root, null, false);
}
pub fn testRemove(comptime T: type, tree_: *AVLTree(T), val: T) void {
var tree = tree_;
_ = tree.remove(val);
std.debug.print("\n删除结点 {} 后AVL 树为\n", .{val});
try inc.PrintUtil.printTree(tree.root, null, false);
}
// Driver Code
pub fn main() !void {
// AVL
var avl_tree = AVLTree(i32){};
avl_tree.init(std.heap.page_allocator);
defer avl_tree.deinit();
//
// AVL
try testInsert(i32, &avl_tree, 1);
try testInsert(i32, &avl_tree, 2);
try testInsert(i32, &avl_tree, 3);
try testInsert(i32, &avl_tree, 4);
try testInsert(i32, &avl_tree, 5);
try testInsert(i32, &avl_tree, 8);
try testInsert(i32, &avl_tree, 7);
try testInsert(i32, &avl_tree, 9);
try testInsert(i32, &avl_tree, 10);
try testInsert(i32, &avl_tree, 6);
//
try testInsert(i32, &avl_tree, 7);
//
// AVL
testRemove(i32, &avl_tree, 8); // 0
testRemove(i32, &avl_tree, 5); // 1
testRemove(i32, &avl_tree, 4); // 2
//
var node = avl_tree.search(7).?;
std.debug.print("\n查找到的结点对象为 {any},结点值 = {}\n", .{node, node.val});
_ = try std.io.getStdIn().reader().readByte();
}

@ -0,0 +1,190 @@
// File: binary_search_tree.zig
// Created Time: 2023-01-15
// Author: sjinzh (sjinzh@gmail.com)
const std = @import("std");
const inc = @import("include");
//
pub fn BinarySearchTree(comptime T: type) type {
return struct {
const Self = @This();
root: ?*inc.TreeNode(T) = null,
mem_arena: ?std.heap.ArenaAllocator = null,
mem_allocator: std.mem.Allocator = undefined, //
//
pub fn init(self: *Self, allocator: std.mem.Allocator, nums: []T) !void {
if (self.mem_arena == null) {
self.mem_arena = std.heap.ArenaAllocator.init(allocator);
self.mem_allocator = self.mem_arena.?.allocator();
}
std.sort.sort(T, nums, {}, comptime std.sort.asc(T)); //
self.root = try self.buildTree(nums, 0, nums.len - 1); //
}
//
pub fn deinit(self: *Self) void {
if (self.mem_arena == null) return;
self.mem_arena.?.deinit();
}
//
fn buildTree(self: *Self, nums: []T, i: usize, j: usize) !?*inc.TreeNode(T) {
if (i > j) return null;
//
var mid = (i + j) / 2;
var node = try self.mem_allocator.create(inc.TreeNode(T));
node.init(nums[mid]);
//
if (mid >= 1) node.left = try self.buildTree(nums, i, mid - 1);
node.right = try self.buildTree(nums, mid + 1, j);
return node;
}
//
fn getRoot(self: *Self) ?*inc.TreeNode(T) {
return self.root;
}
//
fn search(self: *Self, num: T) ?*inc.TreeNode(T) {
var cur = self.root;
//
while (cur != null) {
// cur
if (cur.?.val < num) {
cur = cur.?.right;
// cur
} else if (cur.?.val > num) {
cur = cur.?.left;
//
} else {
break;
}
}
//
return cur;
}
//
fn insert(self: *Self, num: T) !?*inc.TreeNode(T) {
//
if (self.root == null) return null;
var cur = self.root;
var pre: ?*inc.TreeNode(T) = null;
//
while (cur != null) {
//
if (cur.?.val == num) return null;
pre = cur;
// cur
if (cur.?.val < num) {
cur = cur.?.right;
// cur
} else {
cur = cur.?.left;
}
}
// val
var node = try self.mem_allocator.create(inc.TreeNode(T));
node.init(num);
if (pre.?.val < num) {
pre.?.right = node;
} else {
pre.?.left = node;
}
return node;
}
//
fn remove(self: *Self, num: T) ?*inc.TreeNode(T) {
//
if (self.root == null) return null;
var cur = self.root;
var pre: ?*inc.TreeNode(T) = null;
//
while (cur != null) {
//
if (cur.?.val == num) break;
pre = cur;
// cur
if (cur.?.val < num) {
cur = cur.?.right;
// cur
} else {
cur = cur.?.left;
}
}
//
if (cur == null) return null;
// = 0 or 1
if (cur.?.left == null or cur.?.right == null) {
// = 0 / 1 child = null /
var child = if (cur.?.left != null) cur.?.left else cur.?.right;
// cur
if (pre.?.left == cur) {
pre.?.left = child;
} else {
pre.?.right = child;
}
// = 2
} else {
// cur
var nex = self.getInOrderNext(cur.?.right);
var tmp = nex.?.val;
// nex
_ = self.remove(nex.?.val);
// nex cur
cur.?.val = tmp;
}
return cur;
}
// root
fn getInOrderNext(self: *Self, node: ?*inc.TreeNode(T)) ?*inc.TreeNode(T) {
_ = self;
var node_tmp = node;
if (node_tmp == null) return null;
// 访
while (node_tmp.?.left != null) {
node_tmp = node_tmp.?.left;
}
return node_tmp;
}
};
}
// Driver Code
pub fn main() !void {
//
var nums = [_]i32{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
var bst = BinarySearchTree(i32){};
try bst.init(std.heap.page_allocator, &nums);
defer bst.deinit();
std.debug.print("初始化的二叉树为\n", .{});
try inc.PrintUtil.printTree(bst.getRoot(), null, false);
//
var node = bst.search(7);
std.debug.print("\n查找到的结点对象为 {any},结点值 = {}\n", .{node, node.?.val});
//
node = try bst.insert(16);
std.debug.print("\n插入结点 16 后,二叉树为\n", .{});
try inc.PrintUtil.printTree(bst.getRoot(), null, false);
//
_ = bst.remove(1);
std.debug.print("\n删除结点 1 后,二叉树为\n", .{});
try inc.PrintUtil.printTree(bst.getRoot(), null, false);
_ = bst.remove(2);
std.debug.print("\n删除结点 2 后,二叉树为\n", .{});
try inc.PrintUtil.printTree(bst.getRoot(), null, false);
_ = bst.remove(4);
std.debug.print("\n删除结点 4 后,二叉树为\n", .{});
try inc.PrintUtil.printTree(bst.getRoot(), null, false);
_ = try std.io.getStdIn().reader().readByte();
}

@ -0,0 +1,70 @@
// File: binary_tree_dfs.zig
// Created Time: 2023-01-15
// Author: sjinzh (sjinzh@gmail.com)
const std = @import("std");
const inc = @import("include");
var list = std.ArrayList(i32).init(std.heap.page_allocator);
//
fn preOrder(comptime T: type, root: ?*inc.TreeNode(T)) !void {
if (root == null) return;
// 访 -> ->
try list.append(root.?.val);
try preOrder(T, root.?.left);
try preOrder(T, root.?.right);
}
//
fn inOrder(comptime T: type, root: ?*inc.TreeNode(T)) !void {
if (root == null) return;
// 访 -> ->
try inOrder(T, root.?.left);
try list.append(root.?.val);
try inOrder(T, root.?.right);
}
//
fn postOrder(comptime T: type, root: ?*inc.TreeNode(T)) !void {
if (root == null) return;
// 访 -> ->
try postOrder(T, root.?.left);
try postOrder(T, root.?.right);
try list.append(root.?.val);
}
// Driver Code
pub fn main() !void {
//
var mem_arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer mem_arena.deinit();
const mem_allocator = mem_arena.allocator();
//
//
var nums = [_]i32{1, 2, 3, 4, 5, 6, 7};
var root = try inc.TreeUtil.arrToTree(i32, mem_allocator, &nums);
std.debug.print("初始化二叉树\n", .{});
try inc.PrintUtil.printTree(root, null, false);
//
list.clearRetainingCapacity();
try preOrder(i32, root);
std.debug.print("\n前序遍历的结点打印序列 = ", .{});
inc.PrintUtil.printList(i32, list);
//
list.clearRetainingCapacity();
try inOrder(i32, root);
std.debug.print("\n中序遍历的结点打印序列 = ", .{});
inc.PrintUtil.printList(i32, list);
//
list.clearRetainingCapacity();
try postOrder(i32, root);
std.debug.print("\n后续遍历的结点打印序列 = ", .{});
inc.PrintUtil.printList(i32, list);
_ = try std.io.getStdIn().reader().readByte();
}

@ -10,13 +10,15 @@ pub fn TreeNode(comptime T: type) type {
return struct {
const Self = @This();
val: T = undefined,
left: ?*Self = null,
right: ?*Self = null,
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;
}

Loading…
Cancel
Save