Rebalancing an arbitrary BST?

You might want to look into the Day-Stout-Warren algorithm, which is an O(n)-time, O(1)-space algorithm for reshaping an arbitrary binary search tree into a complete binary tree. Intuitively, the algorithm works as follows: Using tree rotations, convert the tree into a degenerate linked list. By applying selective rotations to the linked list, convert the list … Read more

How to implement a binary search tree in Python?

Here is a quick example of a binary insert: class Node: def __init__(self, val): self.l_child = None self.r_child = None self.data = val def binary_insert(root, node): if root is None: root = node else: if root.data > node.data: if root.l_child is None: root.l_child = node else: binary_insert(root.l_child, node) else: if root.r_child is None: root.r_child = … Read more

Difference between AVL trees and splay trees

To answer your questions: What is the difference between AVL trees and splay trees? Both splay trees and AVL trees are binary search trees with excellent performance guarantees, but they differ in how they achieve those guarantee that performance. In an AVL tree, the shape of the tree is constrained at all times such that … Read more

How do you validate a binary search tree?

Actually that is the mistake everybody does in an interview. Leftchild must be checked against (minLimitof node,node.value) Rightchild must be checked against (node.value,MaxLimit of node) IsValidBST(root,-infinity,infinity); bool IsValidBST(BinaryNode node, int MIN, int MAX) { if(node == null) return true; if(node.element > MIN && node.element < MAX && IsValidBST(node.left,MIN,node.element) && IsValidBST(node.right,node.element,MAX)) return true; else return false; … Read more

Why is std::map implemented as a red-black tree?

Probably the two most common self balancing tree algorithms are Red-Black trees and AVL trees. To balance the tree after an insertion/update both algorithms use the notion of rotations where the nodes of the tree are rotated to perform the re-balancing. While in both algorithms the insert/delete operations are O(log n), in the case of … Read more