Skip to content

Instantly share code, notes, and snippets.

@risingsunomi
Created December 30, 2024 02:38
Show Gist options
  • Save risingsunomi/308bf7aeff54b6d1f045f1ecd8c619c4 to your computer and use it in GitHub Desktop.
Save risingsunomi/308bf7aeff54b6d1f045f1ecd8c619c4 to your computer and use it in GitHub Desktop.
zig bfs from X post
const std = @import("std");
const root = @import("root.zig");
fn check_inarray(val: ?*root.TreeNode, arr: *std.ArrayListAligned(?*root.TreeNode, null)) bool {
for (arr.items) |tnode| {
if (tnode.?.val == val.?.val) {
return true;
}
}
return false;
}
pub fn bfs(node: ?*root.TreeNode, queue: *std.ArrayListAligned(?*root.TreeNode, null)) !void {
// bredth first search with a queue
if (node == null) {
return;
}
if (check_inarray(node, queue) == false) {
try queue.append(node);
std.debug.print("{} \n", .{node.?.val});
}
const left_node = node.?.left;
if (left_node != null and check_inarray(left_node, queue) == false) {
try queue.append(left_node);
std.debug.print("{} ", .{left_node.?.val});
}
const right_node = node.?.right;
if (right_node != null and check_inarray(right_node, queue) == false) {
try queue.append(right_node);
std.debug.print("{} \n", .{right_node.?.val});
}
try bfs(left_node, queue);
try bfs(right_node, queue);
}
pub fn main() !void {
// have to build in main or pointers are deleted
// when trying to build in another function then pass to main
var node_6 = root.TreeNode{
.val = 6,
.left = null,
.right = null,
};
var node_5 = root.TreeNode{
.val = 5,
.left = null,
.right = null,
};
var node_4 = root.TreeNode{
.val = 4,
.left = null,
.right = null,
};
var node_3 = root.TreeNode{
.val = 3,
.left = &node_5,
.right = &node_6,
};
var node_2 = root.TreeNode{
.val = 2,
.left = &node_4,
.right = null,
};
var node_1 = root.TreeNode{
.val = 1,
.left = &node_2,
.right = &node_3,
};
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const alloc = gpa.allocator();
defer _ = gpa.deinit();
var queue = std.ArrayList(?*root.TreeNode).init(alloc);
defer queue.deinit();
try bfs(&node_1, &queue);
}
const std = @import("std");
pub const TreeNode = struct {
val: u32,
left: ?*TreeNode,
right: ?*TreeNode,
};
test "tree node" {
var tree_node_last = TreeNode{
.val = 10,
.left = null,
.right = null,
};
const tree_node_first = TreeNode{
.val = 5,
.left = null,
.right = &tree_node_last,
};
try std.testing.expectEqual(@as(i32, 5), tree_node_first.val);
try std.testing.expectEqual(@as(i32, 10), tree_node_first.right.?.val);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment