Créer une présentation
Télécharger la présentation

Télécharger la présentation
## BST Trees Saurav Karmakar

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -

**5**3 7 1 2 8 BST TreesSaurav Karmakar**5**3 8 1 4 9 Binary search tree (BST) • A binary search tree is a binary tree in which every node satisfies the following: • the key of every node in the left subtree is smaller than the key of this node • the key of every node in the right subtree is larger than the key of this node • Note: Duplication nodes ?**5**3 8 1 4 9 Binary search tree • The left subtree and the right subtree are also BST (Recursion) • No two nodes in a BST have the same key (??) • If we traverse a BST inorder, we list the keys in ascending order**8**1 4 12 9 2 10 14 6 7 1 9 11 3 7 15 5 13 10 3 2 12 5 6 14 3 8 16 4 15 Some examples 8**This is an incorrect check of BST.**5 Every node satisfies the following: -- the key of the left node is smaller than the its own key -- the key of the right node is larger than its own key 3 8 1 7 9 Is this a BST? This is NOT BST!**To find a key in a BST, we start at the root. Compare the**target key with the key of the current node. - target == p->key, Done. - target < p->key, go left - target > p->key, go right 8 4 12 10 2 14 6 1 9 11 3 7 15 13 5 Note that the principle behind is similar to binary search... Find 5 Search BST target**Recursive BST Search Algorithm**// Algorithm for tree search // Finds the position of a node with the specified key TreeSearch(root, key); begin if root == nil then position := nil else if target == root->key then position := root else if target < root->key then TreeSearch(root->left, target) else TreeSearch(root->right, target); end;**C++ Implementation of BST Search**// Internal method to find an item in a subtree. // x is item to search for // t is the node that roots the tree // Return node containing the matched item. template <class Comparable> BinaryNode<Comparable> * BinarySearchTree<Comparable>:: find( const Comparable & x, Node *t ) const { while( t != NULL ) { if( x < t->element ) // element is the key value for each node t = t->left; else if( t->element < x ) t = t->right; else return t; // Match } return NULL; // Not found }**8**4 12 2 10 6 14 1 9 11 3 7 15 13 5 Balance tree The efficiency of BST search depends on the shape of the tree. If the tree is balance, (minimum height, very bushy), the search is fast (log(n) steps). If the tree is a long narrow chain, the search is slow (n steps) 1 15 2 14 Compare this with sequential and binary search ... 3 log(16)=4 4 5 13**Binary Search Tree Class - FindMin/Max**template <class Comparable> BinaryNode<Comparable> * BinarySearchTree<Comparable>::findMin( Node *t ) const{ if( t != NULL ){ while( t->left != NULL ) t = t->left; // the leftmost node } return t; } _ template <class Comparable> BinaryNode<Comparable> * BinarySearchTree<Comparable>::findMax( Node *t ) const{ If( t != NULL ) while( t->right != NULL ) t = t->right; // the rightmost node return t; }**Insert & Delete in BST**• First we’ll study simple-minded Insert and Delete procedure. They may result in highly unbalanced tree. • Then we’ll study a special kind of BST called AVL tree which maintains near balance in inserting and deleting.**10**5 12 4 7 14 15 2 1 9 3 17 8 Insert in BST (recursive version) • // Internal method to insert into a subtree • // x is the item to insert • // t is the node that roots the tree • // Set the new root, if no root present • // Throw an exception if x is already in t • template <class Comparable> • void BinarySearchTree<Comparable>:: • insert( const Comparable & x, Node * & t ) const { • if( t == NULL ) • t = new Node( x, NULL, NULL ); • else if( x < t->element ) • insert( x, t->left ); • else if( x > t->element) • insert( x, t->right ); • else • throw DuplicateItemException( ); • } 6 16 New nodes are always added as leaves.****Delete in BST Case 1: If it has no children, that is, it is a leaf, we just remove it.**L** L Delete in BST Case 2: If it has only one child, (i.e. only one subtree), we splice out it. That is, we attach that subtree to the parent of the node.**10**10 10 7 5 12 12 7 12 7 14 14 6 9 6 9 17 6 9 17 17 15 15 15 16 16 16 Delete in BST, examples Case 2: delete a node that has only one subtree.**Min in R** L R’ L R Delete in BST • Case 3: If it has nonempty left and right subtrees. • Find the minimum node in right subtree, then copy its key value to X, and remove the min node from right subtree. • Or Find the max node in left subtree, then copy its key value to X, and remove the max node from left subtree.**4**2 3 1 Delete Tree, example 10 10 5 12 6 12 4 8 8 16 16 2 6 9 7 9 14 14 3 7 1 15 15 Case 3: delete a node that has nonempty left and right subtrees.**Delete in BST**template <class Comparable> void BinarySearchTree<Comparable>:: remove( const Comparable & x, Node * & t ) const { if( t == NULL ) throw ItemNotFoundException( ); if( x < t->element ) remove( x, t->left ); else if( t->element < x ) remove( x, t->right ); else if( t->left != NULL && t->right != NULL ) { //case 3 t->element = findMin( t->right )->element; removeMin( t->right ); // Remove minimum } else{ // case 1, 2 BinaryNode<Comparable> *oldNode = t; t = ( t->left != NULL ) ? t->left : t->right; // Reroot t delete oldNode; // delete old root } }**Order statistics**• findKth smallest element problem based on the consider of relationship of node size and K. X SL SL SR SR SR X X SL If K == SL +1, it is the root If K > SL +1, it is the K-(SL +1)th smallest on the right subtree If K < SL +1, it is the Kth samllest element in the left subtree Note: SL is the size of the left subtree**Binary Search Tree**• Binary search tree, using simple insert and delete procedures • If the tree is nearly balanced • add - fastO(log n) • delete a target - fastO(log n) • search - fastO(log n) • If the tree is highly unbalanced, it becomes a singly linked list (the worst case) • add, delete and search - slowO(n)effectively using sequential search to find a location**AVL Tree (Adelson-Velskii & Landis)**• AVL Tree are BST with an additional balance condition to ensure the depth of the tree is O(log2N) • Balance Condition: for any node in the tree, the height of the left and right subtrees can differ by at most 1. • Must ensure that after insertion and deletion of a node, the balance condition is preserved**Adding/deleteing node from AVL Tree*** Add a node connected to some node? * Delete some node? • After an insertion, the nodes on the path from the insertion point to the root can have their balances altered. • Rotationrestores local balance**Signle rotation**k2 k1 k1 C k2 A A B B C**Rotate Binary Tree with Left Child**template <class comparable> Void BST<comparable>::rotateWithLeftChild(Node * &k2) const { Node *k1 = k2left; k2left = k1right; k1right = k2; k2 = k1; }**3**3 1 5 1 7 2 4 7 5 9 2 6 9 4 6 8 x y 8 A y x C B C A B Single Rotation**3**3 1 5 1 8 2 4 8 5 9 2 6 9 4 6 7 7 Single Rotation Doesn’t Work in Some Cases**3**3 1 5 1 6 2 4 8 5 8 2 6 9 4 7 9 7 x z A y x y z D B C A B C D Double Rotation**Red-black trees**This data structure requires an extra one-bit color field in each node. Red-black properties: 1. Every node is either red or black. 2. The root and leaves (NIL’s) are black. 3. If a node is red, then its parent is black. 4. All simple paths from any nodexto a descendant leaf have the same number of black nodes = black-height(x).**Example of a red-black tree**1. Every node is either red or black.**Example of a red-black tree**2. The root and leaves (NIL’s) are black.**Example of a red-black tree**3. If a node is red, then its parent is black.**Example of a red-black tree**4. All simple paths from any node xto a descendant leaf have the same number of black nodes = black-height(x).**Height of a red-black tree**Theorem.A red-black tree with n keys has height h ≤ 2 lg(n + 1).**Query operations**Corollary.The queries SEARCH, MIN, MAX, SUCCESSOR, and PREDECESSOR all run in O(lg n) time on a red-black tree withn nodes.**Modifying operations**The operations INSERT and DELETE cause modifications to the red-black tree: • the operation itself, • color changes, • restructuring the links of the tree via “rotations”.**Rotations**Rotations maintain the inorder ordering of keys: • a ∈ α, b ∈ β, c ∈ γ ⇒ a ≤ A ≤ b ≤ B ≤ c. A rotation can be performed in O(1) time.**Insertion into a red-black tree**IDEA:Insert x in tree. Color xred. Only redblack property 3 might be violated. Move the violation up the tree by recoloring until it can be fixed with rotations and recoloring. Example:**Insertion into a red-black tree**IDEA:Insert x in tree. Color xred. Only redblack property 3 might be violated. Move the violation up the tree by recoloring until it can be fixed with rotations and recoloring. Example: • Insert x =15. • Recolor, moving the violation up the tree.**Insertion into a red-black tree**IDEA:Insert x in tree. Color xred. Only redblack property 3 might be violated. Move the violation up the tree by recoloring until it can be fixed with rotations and recoloring. Example: • Insert x =15. • Recolor, moving the violation up the tree. • RIGHT-ROTATE(18).**Insertion into a red-black tree**IDEA:Insert x in tree. Color xred. Only redblack property 3 might be violated. Move the violation up the tree by recoloring until it can be fixed with rotations and recoloring. Example: • Insert x =15. • Recolor, moving the violation up the tree. • RIGHT-ROTATE(18). • LEFT-ROTATE(7) and recolor.**Insertion into a red-black tree**IDEA:Insert xin tree. Color xred. Only redblack property 3 might be violated. Move the violation up the tree by recoloring until it can be fixed with rotations and recoloring. Example: • Insert x =15. • Recolor, moving the violation up the tree. • RIGHT-ROTATE(18). • LEFT-ROTATE(7) and recolor.**Pseudocode**RB-INSERT(T, x) TREE-INSERT(T, x) color[x] ← RED ⊳ only RB property 3 can be violated while x ≠ root[T] and color[p[x]] = RED do if p[x] = left[p[p[x]] then y ← right[p[p[x]]⊳y = aunt/uncle of x if color[y]= RED then 〈Case 1〉 else if x = right[p[x]] then 〈Case 2〉⊳ Case 2 falls into Case 3 〈Case 3〉 else 〈“then” clause with “left” and “right” swapped〉 color[root[T]]← BLACK**Graphical notation**Let denote a subtree with a black root. All s have the same black-height.**Case 1**Push C’s black onto Aand D, and recurse, since C’s parent may be red. (Or, children of Aare swapped.)**Case 2**Transform to Case 3.**Case 3**Done! No more violations of RB property 3 are possible.**Red Black Tree (Insertion Example)**• Insert 10 – root 10**Red Black Tree (Insertion Example)**• Insert 10 – root (external nodes not shown) 10**Red Black Tree**• Insert 85 10 85