Skip to Content
Hands-On Data Structures and Algorithms with Rust
book

Hands-On Data Structures and Algorithms with Rust

by Claus Matzinger
January 2019
Intermediate to advanced
316 pages
8h 8m
English
Packt Publishing
Content preview from Hands-On Data Structures and Algorithms with Rust

Balancing the tree

After the node is added properly, fix_tree() takes care of restoring the red-black tree's properties—iteratively. While this is nicely descriptive and demonstrative it is long, so let's break it up into parts. Initially, the function determines whether it should stop (or not even start)—which only happens in two cases:

  • When it's already the root node
  • When the parent of the currently inspected node is red

Clearly, the former is the regular exit criterion as well, as the loop optimizes and moves the current pointer (n as in node) from the bottom toward the root of the tree to stop there:

fn fix_tree(&mut self, inserted: BareTree) -> Tree {    let mut not_root = inserted.borrow().parent.is_some();    let root = if not_root {
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Hands-On Data Structures and Algorithms in Rust

Hands-On Data Structures and Algorithms in Rust

Matthew Stoodley

Publisher Resources

ISBN: 9781788995528Supplemental Content