avl树

An AVL Tree is a self-balancing binary search tree. The heights of any two sibling nodes must differ by at most one; the tree may rebalance itself after insertion or deletion to uphold this property.

Properties

  • Worst/Average time complexity for basic operations: O(log n)
  • Worst/Average space complexity: O(n)
  1. use std::{
  2. cmp::{max, Ordering},
  3. iter::FromIterator,
  4. mem,
  5. ops::Not,
  6. };
  7. /// An internal node of an `AVLTree`.
  8. struct AVLNode<T: Ord> {
  9. value: T,
  10. height: usize,
  11. left: Option<Box<AVLNode<T>>>,
  12. right: Option<Box<AVLNode<T>>>,
  13. }
  14. /// A set based on an AVL Tree.
  15. ///
  16. /// An AVL Tree is a self-balancing binary search tree. It tracks the height of each node
  17. /// and performs internal rotations to maintain a height difference of at most 1 between
  18. /// each sibling pair.
  19. pub struct AVLTree<T: Ord> {
  20. root: Option<Box<AVLNode<T>>>,
  21. length: usize,
  22. }
  23. /// Refers to the left or right subtree of an `AVLNode`.
  24. #[derive(Clone, Copy)]
  25. enum Side {
  26. Left,
  27. Right,
  28. }
  29. impl<T: Ord> AVLTree<T> {
  30. /// Creates an empty `AVLTree`.
  31. pub fn new() -> AVLTree<T> {
  32. AVLTree {
  33. root: None,
  34. length: 0,
  35. }
  36. }
  37. /// Returns `true` if the tree contains a value.
  38. pub fn contains(&self, value: &T) -> bool {
  39. let mut current = &self.root;
  40. while let Some(node) = current {
  41. current = match value.cmp(&node.value) {
  42. Ordering::Equal => return true,
  43. Ordering::Less => &node.left,
  44. Ordering::Greater => &node.right,
  45. }
  46. }
  47. false
  48. }
  49. /// Adds a value to the tree.
  50. ///
  51. /// Returns `true` if the tree did not yet contain the value.
  52. pub fn insert(&mut self, value: T) -> bool {
  53. let inserted = insert(&mut self.root, value);
  54. if inserted {
  55. self.length += 1;
  56. }
  57. inserted
  58. }
  59. /// Removes a value from the tree.
  60. ///
  61. /// Returns `true` if the tree contained the value.
  62. pub fn remove(&mut self, value: &T) -> bool {
  63. let removed = remove(&mut self.root, value);
  64. if removed {
  65. self.length -= 1;
  66. }
  67. removed
  68. }
  69. /// Returns the number of values in the tree.
  70. pub fn len(&self) -> usize {
  71. self.length
  72. }
  73. /// Returns `true` if the tree contains no values.
  74. pub fn is_empty(&self) -> bool {
  75. self.length == 0
  76. }
  77. /// Returns an iterator that visits the nodes in the tree in order.
  78. fn node_iter(&self) -> NodeIter<T> {
  79. let cap = self.root.as_ref().map_or(0, |n| n.height);
  80. let mut node_iter = NodeIter {
  81. stack: Vec::with_capacity(cap),
  82. };
  83. // Initialize stack with path to leftmost child
  84. let mut child = &self.root;
  85. while let Some(node) = child {
  86. node_iter.stack.push(node.as_ref());
  87. child = &node.left;
  88. }
  89. node_iter
  90. }
  91. /// Returns an iterator that visits the values in the tree in ascending order.
  92. pub fn iter(&self) -> Iter<T> {
  93. Iter {
  94. node_iter: self.node_iter(),
  95. }
  96. }
  97. }
  98. /// Recursive helper function for `AVLTree` insertion.
  99. fn insert<T: Ord>(tree: &mut Option<Box<AVLNode<T>>>, value: T) -> bool {
  100. if let Some(node) = tree {
  101. let inserted = match value.cmp(&node.value) {
  102. Ordering::Equal => false,
  103. Ordering::Less => insert(&mut node.left, value),
  104. Ordering::Greater => insert(&mut node.right, value),
  105. };
  106. if inserted {
  107. node.rebalance();
  108. }
  109. inserted
  110. } else {
  111. *tree = Some(Box::new(AVLNode {
  112. value,
  113. height: 1,
  114. left: None,
  115. right: None,
  116. }));
  117. true
  118. }
  119. }
  120. /// Recursive helper function for `AVLTree` deletion.
  121. fn remove<T: Ord>(tree: &mut Option<Box<AVLNode<T>>>, value: &T) -> bool {
  122. if let Some(node) = tree {
  123. let removed = match value.cmp(&node.value) {
  124. Ordering::Less => remove(&mut node.left, value),
  125. Ordering::Greater => remove(&mut node.right, value),
  126. Ordering::Equal => {
  127. *tree = match (node.left.take(), node.right.take()) {
  128. (None, None) => None,
  129. (Some(b), None) | (None, Some(b)) => Some(b),
  130. (Some(left), Some(right)) => Some(merge(left, right)),
  131. };
  132. return true;
  133. }
  134. };
  135. if removed {
  136. node.rebalance();
  137. }
  138. removed
  139. } else {
  140. false
  141. }
  142. }
  143. /// Merges two trees and returns the root of the merged tree.
  144. fn merge<T: Ord>(left: Box<AVLNode<T>>, right: Box<AVLNode<T>>) -> Box<AVLNode<T>> {
  145. let mut op_right = Some(right);
  146. // Guaranteed not to panic since right has at least one node
  147. let mut root = take_min(&mut op_right).unwrap();
  148. root.left = Some(left);
  149. root.right = op_right;
  150. root.rebalance();
  151. root
  152. }
  153. /// Removes the smallest node from the tree, if one exists.
  154. fn take_min<T: Ord>(tree: &mut Option<Box<AVLNode<T>>>) -> Option<Box<AVLNode<T>>> {
  155. if let Some(mut node) = tree.take() {
  156. // Recurse along the left side
  157. if let Some(small) = take_min(&mut node.left) {
  158. // Took the smallest from below; update this node and put it back in the tree
  159. node.rebalance();
  160. *tree = Some(node);
  161. Some(small)
  162. } else {
  163. // Take this node and replace it with its right child
  164. *tree = node.right.take();
  165. Some(node)
  166. }
  167. } else {
  168. None
  169. }
  170. }
  171. impl<T: Ord> AVLNode<T> {
  172. /// Returns a reference to the left or right child.
  173. fn child(&self, side: Side) -> &Option<Box<AVLNode<T>>> {
  174. match side {
  175. Side::Left => &self.left,
  176. Side::Right => &self.right,
  177. }
  178. }
  179. /// Returns a mutable reference to the left or right child.
  180. fn child_mut(&mut self, side: Side) -> &mut Option<Box<AVLNode<T>>> {
  181. match side {
  182. Side::Left => &mut self.left,
  183. Side::Right => &mut self.right,
  184. }
  185. }
  186. /// Returns the height of the left or right subtree.
  187. fn height(&self, side: Side) -> usize {
  188. self.child(side).as_ref().map_or(0, |n| n.height)
  189. }
  190. /// Returns the height difference between the left and right subtrees.
  191. fn balance_factor(&self) -> i8 {
  192. let (left, right) = (self.height(Side::Left), self.height(Side::Right));
  193. if left < right {
  194. (right - left) as i8
  195. } else {
  196. -((left - right) as i8)
  197. }
  198. }
  199. /// Recomputes the `height` field.
  200. fn update_height(&mut self) {
  201. self.height = 1 + max(self.height(Side::Left), self.height(Side::Right));
  202. }
  203. /// Performs a left or right rotation.
  204. fn rotate(&mut self, side: Side) {
  205. let mut subtree = self.child_mut(!side).take().unwrap();
  206. *self.child_mut(!side) = subtree.child_mut(side).take();
  207. self.update_height();
  208. // Swap root and child nodes in memory
  209. mem::swap(self, subtree.as_mut());
  210. // Set old root (subtree) as child of new root (self)
  211. *self.child_mut(side) = Some(subtree);
  212. self.update_height();
  213. }
  214. /// Performs left or right tree rotations to balance this node.
  215. fn rebalance(&mut self) {
  216. self.update_height();
  217. let side = match self.balance_factor() {
  218. -2 => Side::Left,
  219. 2 => Side::Right,
  220. _ => return,
  221. };
  222. let subtree = self.child_mut(side).as_mut().unwrap();
  223. // Left-Right and Right-Left require rotation of heavy subtree
  224. if let (Side::Left, 1) | (Side::Right, -1) = (side, subtree.balance_factor()) {
  225. subtree.rotate(side);
  226. }
  227. // Rotate in opposite direction of heavy side
  228. self.rotate(!side);
  229. }
  230. }
  231. impl<T: Ord> Default for AVLTree<T> {
  232. fn default() -> Self {
  233. Self::new()
  234. }
  235. }
  236. impl Not for Side {
  237. type Output = Side;
  238. fn not(self) -> Self::Output {
  239. match self {
  240. Side::Left => Side::Right,
  241. Side::Right => Side::Left,
  242. }
  243. }
  244. }
  245. impl<T: Ord> FromIterator<T> for AVLTree<T> {
  246. fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
  247. let mut tree = AVLTree::new();
  248. for value in iter {
  249. tree.insert(value);
  250. }
  251. tree
  252. }
  253. }
  254. /// An iterator over the nodes of an `AVLTree`.
  255. ///
  256. /// This struct is created by the `node_iter` method of `AVLTree`.
  257. struct NodeIter<'a, T: Ord> {
  258. stack: Vec<&'a AVLNode<T>>,
  259. }
  260. impl<'a, T: Ord> Iterator for NodeIter<'a, T> {
  261. type Item = &'a AVLNode<T>;
  262. fn next(&mut self) -> Option<Self::Item> {
  263. if let Some(node) = self.stack.pop() {
  264. // Push left path of right subtree to stack
  265. let mut child = &node.right;
  266. while let Some(subtree) = child {
  267. self.stack.push(subtree.as_ref());
  268. child = &subtree.left;
  269. }
  270. Some(node)
  271. } else {
  272. None
  273. }
  274. }
  275. }
  276. /// An iterator over the items of an `AVLTree`.
  277. ///
  278. /// This struct is created by the `iter` method of `AVLTree`.
  279. pub struct Iter<'a, T: Ord> {
  280. node_iter: NodeIter<'a, T>,
  281. }
  282. impl<'a, T: Ord> Iterator for Iter<'a, T> {
  283. type Item = &'a T;
  284. fn next(&mut self) -> Option<&'a T> {
  285. match self.node_iter.next() {
  286. Some(node) => Some(&node.value),
  287. None => None,
  288. }
  289. }
  290. }
  291. #[cfg(test)]
  292. mod tests {
  293. use super::AVLTree;
  294. /// Returns `true` if all nodes in the tree are balanced.
  295. fn is_balanced<T: Ord>(tree: &AVLTree<T>) -> bool {
  296. tree.node_iter()
  297. .all(|n| (-1..=1).contains(&n.balance_factor()))
  298. }
  299. #[test]
  300. fn len() {
  301. let tree: AVLTree<_> = (1..4).collect();
  302. assert_eq!(tree.len(), 3);
  303. }
  304. #[test]
  305. fn contains() {
  306. let tree: AVLTree<_> = (1..4).collect();
  307. assert!(tree.contains(&1));
  308. assert!(!tree.contains(&4));
  309. }
  310. #[test]
  311. fn insert() {
  312. let mut tree = AVLTree::new();
  313. // First insert succeeds
  314. assert!(tree.insert(1));
  315. // Second insert fails
  316. assert!(!tree.insert(1));
  317. }
  318. #[test]
  319. fn remove() {
  320. let mut tree: AVLTree<_> = (1..8).collect();
  321. // First remove succeeds
  322. assert!(tree.remove(&4));
  323. // Second remove fails
  324. assert!(!tree.remove(&4));
  325. }
  326. #[test]
  327. fn sorted() {
  328. let tree: AVLTree<_> = (1..8).rev().collect();
  329. assert!((1..8).eq(tree.iter().map(|&x| x)));
  330. }
  331. #[test]
  332. fn balanced() {
  333. let mut tree: AVLTree<_> = (1..8).collect();
  334. assert!(is_balanced(&tree));
  335. for x in 1..8 {
  336. tree.remove(&x);
  337. assert!(is_balanced(&tree));
  338. }
  339. }
  340. }