public void Balance(AVLNode <T> current) { current.FixHeight(); if (current.GetBalance() < -1) { if (current.Left.GetBalance() > 0) { RotateLeft(current.Left); } RotateRight(current); } else if (current.GetBalance() > 1) { //too heavy on right, rotate left if (current.Right.GetBalance() < 0) { RotateRight(current.Right); } RotateLeft(current); } if (current.Parent != null) { Balance(current.Parent); } }
private AVLNode <T> RotateRight(AVLNode <T> node) { var parent = node.Parent; var child = node.Left; var cat = child.Right; //child child.Right = node; child.Parent = parent; //node stuff node.Left = cat; node.Parent = child; if (node == root) { root = child; } //cat stuff if (cat != null) { cat.Parent = node; } //parent stuff if (parent != null) { if (parent.Left == node) { parent.Left = child; } else { parent.Right = child; } } node.FixHeight(); child.FixHeight(); return(child); }
private AVLNode <T> RotateLeft(AVLNode <T> node) { var parent = node.Parent; var child = node.Right; var childleft = child.Left; //Node node.Right = childleft; node.Parent = child; //Child child.Left = node; child.Parent = parent; if (node == root) { root = child; } //Possible GChild if (childleft != null) { childleft.Parent = node; } //Possible Parent if (parent != null) { if (parent.Right == node) { parent.Right = child; } else { parent.Left = child; } } node.FixHeight(); child.FixHeight(); return(child); }