Sfoglia il codice sorgente

test(node): test node height field

Danilo Gómez 1 anno fa
parent
commit
7cf8e34770
1 ha cambiato i file con 21 aggiunte e 0 eliminazioni
  1. 21 0
      src/node.rs

+ 21 - 0
src/node.rs

@@ -137,6 +137,7 @@ impl<T: Ord> Node<T> {
 #[cfg(test)]
 mod tests {
     use super::Node;
+    use std::cmp::max;
 
     #[test]
     fn is_sorted() {
@@ -178,4 +179,24 @@ mod tests {
         }
         traverse(&root);
     }
+
+    #[test]
+    fn test_height() {
+        let values = vec![5, 3, 7, 1, 4, 6, 9];
+        let mut root = Node::new(values[0]);
+        for v in values[1..].iter() {
+            root.insert(*v);
+        }
+        fn traverse(node: &Node<i32>) -> i32 {
+            let lheight = node.left.as_ref().map_or(0, |left| traverse(left.as_ref()));
+            let rheight = node
+                .right
+                .as_ref()
+                .map_or(0, |right| traverse(right.as_ref()));
+            let height = max(lheight, rheight) + 1;
+            assert_eq!(node.height, height);
+            height
+        }
+        traverse(&root);
+    }
 }