2 个版本
0.1.1 | 2020 年 12 月 27 日 |
---|---|
0.1.0 | 2020 年 12 月 9 日 |
#1607 在 数据结构
24KB
367 行
lineartree
一个简单易用的 Rust 树数据结构。
该软件包使用单个向量来存储所有节点,因此得名。基本上它是一个 Vec<Node<T>>
,其中每个 Node<T>
都有父节点和子节点的索引。
此外,还有一些便利函数,可以迭代节点的深度优先和广度优先遍历、查找子节点等。
快速开始
创建树
use lineartree::{Tree, NodeRef};
/* This builds the following tree
* "/"
* / \
* etc usr
* / \
* bin lib
*/
let mut tree = Tree::new();
// Trees usually have a root node
let fs_root = tree.root("/")?;
// Using .root() or .node() return a NodeRef object
// which can be later used to identify and manipulate
// node values.
let usr = tree.node("usr");
tree.append_child(fs_root, usr)?;
// Add multiple children at once
let bin = tree.node("bin");
let lib = tree.node("lib");
tree.append_children(usr, &[bin, lib])?;
// You can also add nodes to a parent in a single go
let etc = tree.child_node(fs_root, "etc")?;
获取、更改和删除节点
// Get node values (this is O(1))
assert_eq!(tree.get(lib), Some(&"lib"));
assert_eq!(tree.get(lib), Some(&"lib"));
assert_eq!(tree.get_mut(lib), Some(&mut "lib"));
// Remove node, this won't resize the underlying Vec
// because otherwise node references will be invalidated.
tree.remove(etc)?;
获取节点数量
// .len() is also O(1)
assert_eq!(tree.len(), 4);
遍历树
// Here are the basic hierarchical operators
assert_eq!(tree.get_parent(usr)?, Some(fs_root));
assert_eq!(
tree.get_children(usr).unwrap().collect::<Vec<NodeRef>>(),
vec![bin, lib],
);
// Iterate depth first over a node children.
// Use .depth_first() to iterate the entire tree.
for node in tree.depth_first_of(usr)? {
// ...
}