private AvlNode Delete(AvlNode tree, string key) { if (tree == null) { return(null); } if (string.Compare(key, tree.Key) > 0) { tree.Right = Delete(tree.Right, key); } else if (string.Compare(key, tree.Key) < 0) { tree.Left = Delete(tree.Left, key); } else { if (tree.Left == null && tree.Right == null) { return(null); } else if (tree.Left == null && tree.Right != null) { return(tree.Right); } else if (tree.Left != null && tree.Right == null) { return(tree.Left); } else { AvlNode temp = MaxValueNode(tree.Left); tree.Key = temp.Key; tree.Value = temp.Value; tree.Left = Delete(tree.Left, temp.Key); } } return(Balance(tree)); }
static AvlNode CloneNode(AvlNode node) { if (node == null) { return(null); } var ret = new AvlNode { Left = node.Left, Right = node.Right, Parent = node.Parent, Value = node.Value, Height = node.Height }; return(ret); }
private bool Contains(AvlNode tree, string key, ref int value) { if (tree == null) { return(false); } else if (string.Compare(key, tree.Key) > 0) { return(Contains(tree.Right, key, ref value)); } else if (string.Compare(key, tree.Key) < 0) { return(Contains(tree.Left, key, ref value)); } else { value = tree.Value; return(true); } }
private AvlNode Insert(AvlNode tree, string key, int value) { if (tree == null) { return new AvlNode { Key = key, Value = value } } ; else if (string.Compare(key, tree.Key) > 0) { tree.Right = Insert(tree.Right, key, value); } else if (string.Compare(key, tree.Key) < 0) { tree.Left = Insert(tree.Left, key, value); } return(Balance(tree)); }
static void Add(AvlNode node, int value, AvlNode parent = null) { var newNode = new AvlNode { Left = null, Right = null, Value = value, Parent = node }; if (value >= node.Value) { if (node.Right == null) { node.Right = newNode; MaintainHeightAfterInsert(newNode); Modify(newNode); } else { Add(node.Right, value, node); } } else { if (node.Left == null) { node.Left = newNode; MaintainHeightAfterInsert(newNode); Modify(newNode); } else { Add(node.Left, value, node); } } }
private AvlNode Balance(AvlNode tree) { FixHeight(tree); if (BalanceFactor(tree) == 2) { if (BalanceFactor(tree.Right) < 0) { tree.Right = RotateRight(tree.Right); } return(RotateLeft(tree)); } if (BalanceFactor(tree) == -2) { if (BalanceFactor(tree.Left) > 0) { tree.Left = RotateLeft(tree.Left); } return(RotateRight(tree)); } return(tree); }
public void Clear() { MakeEmpty(_root); _root = null; }
public void Remove(string key) { _root = Delete(_root, key); }
public void Add(string key, int value) { _root = Insert(_root, key, value); }
private int BalanceFactor(AvlNode tree) { return(Height(tree.Right) - Height(tree.Left)); }
private void FixHeight(AvlNode tree) { tree.Height = Math.Max(Height(tree.Left), Height(tree.Right)) + 1; }
private int Height(AvlNode tree) { return(tree == null ? -1 : tree.Height); }