public void GetBalanceFactor_ForSeveralNodesInSampleTree_ExpectsCorrectValues() { /* The constructed tree is not AVL, however the method GetBalanceFactor should work regardless. */ var A = new AVLTreeNode <int, string>(50, "A"); var B = new AVLTreeNode <int, string>(20, "B"); var C = new AVLTreeNode <int, string>(10, "C"); var D = new AVLTreeNode <int, string>(40, "D"); var E = new AVLTreeNode <int, string>(30, "E"); A.Parent = null; A.LeftChild = B; A.RightChild = null; B.Parent = A; B.LeftChild = C; B.RightChild = D; C.Parent = B; C.LeftChild = null; C.RightChild = null; D.Parent = B; D.LeftChild = E; D.RightChild = null; E.Parent = D; E.LeftChild = null; E.RightChild = null; Assert.AreEqual(-3, _tree.ComputeBalanceFactor(A)); Assert.AreEqual(1, _tree.ComputeBalanceFactor(B)); Assert.AreEqual(0, _tree.ComputeBalanceFactor(C)); Assert.AreEqual(-1, _tree.ComputeBalanceFactor(D)); Assert.AreEqual(0, _tree.ComputeBalanceFactor(E)); }
/// <summary> /// Checks whether all the nodes in the AVL tree have expected balance factors between -1 and 1. /// </summary> /// <typeparam name="TKey">Type of the keys stored in the tree. </typeparam> /// <typeparam name="TValue">Type of the values stored in the tree. </typeparam> /// <param name="tree">An AVL tree</param> /// <param name="nodes">List of all the nodes in the tree. </param> /// <returns>True if the nodes all have expected balance factors, and false otherwise. </returns> public bool HasExpectedBalanceFactor <TKey, TValue>(AVLTree <TKey, TValue> tree, List <AVLTreeNode <TKey, TValue> > nodes) where TKey : IComparable <TKey>, IEquatable <TKey> { foreach (AVLTreeNode <TKey, TValue> node in nodes) { int balanceFactor = tree.ComputeBalanceFactor(node); Assert.IsTrue(balanceFactor >= -1 && balanceFactor <= 1); } return(true); }