SlideShare une entreprise Scribd logo
1  sur  43
Binary Search Tree
Preliminaries
Search
 Array
 List
 Stack?
 Queue?
 For large amounts of input, the linear access
  time of lists is prohibitive
Preliminaries
Tree
 A collection of nodes
 The collection can be empty
 Otherwise, the tree consists of a distinguished
  node r, called the root, and zero or more
  (sub)trees T1, T2, T3, …, Tk, each of whose
  roots are connected by a directed edge to r.
 The root of each subtree is said to be a child
  of r, and r is the parent of each subtree root
Preliminaries
              root




T1   T2         T3   T4       Tk
                          …
Preliminaries
Tree
 A tree is a collection of n nodes, one of which
  is the root, and n-1 edges.
   Each edge connects some node to its parent and
    every node except the root has one parent
Preliminaries
                           ROOT

                            A
       INTERNAL NODES                       INTERNAL NODES

 B       C           D                  E           F        G

LEAF   LEAF
               H                I       J       L   M   N        O


              LEAF       LEAF                       LEAVES
                                    P       Q

                                    LEAVES
Binary Tree
A binary tree is a tree in which no node
 can have more than two children
                  root




             TL          TR
Binary Tree
            A



    D               E



H       I       J       L


    P               Q
Implementation
 Node
class node{
public:
   int item;
   node *left;
   node *right;
   node(int x) { item = x; left = right = NULL; }
   node( ) { item = 0; left = right = NULL; }
};
Expression Trees
(a+b*c)+((d*e+f)*g)       +


      +                                   *



a            *                        +       g



      b               c           *       f



                              d       e
Binary Search Tree
 An application of binary trees is their use in
  searching
 Let us assume that each node in the tree is
  assigned a key value, and assume that this is an
  integer
 The property that makes a binary tree into a
  binary search tree is that for every node, X, in
  the tree, the values of all keys in the left subtree
  are smaller than the key value in X, and the
  values of all keys in the right subtree are larger
  than the key value in X.
Binary Search Tree
         6               6



    2        8       2       8



1        4       1       4



    3                3       7
Binary Search Tree
class BST{
private:
   int size;
   node *root;
public:
   BST() {size = 0; root = NULL;}
   void insert(int);
   bool delete(int);
   bool search(int);
   int minimum();
   int maximum();
};
Binary Search Tree (Search)
                      Search for 10
             6



         2       8



     1       4        20



         3       10         50
Binary Search Tree (Search)
bool BST::search(int x){
  node *tmp = root;
  while(tmp!=NULL){
      if(x == tmp->item)
              return true;
      if(x < tmp->item)
              tmp = tmp->left;
      else
              tmp = tmp->right;
  }
  return false;
}
Binary Search Tree (Minimum)
                6



            2       8



       1        4        20



  -5        3       10        50


       -1
Binary Search Tree (Minimum)
int BST::minimum(){
  node *tmp = root;
  while(tmp->left != NULL)
     tmp = tmp -> left;
  return temp->item;
}
Binary Search Tree (Insert)
                            6

Insert 20, 10, 50
                        2       8



                    1       4        20



                        3       10        50
Binary Search Tree (Insert)
Let’s insert 6, 2, 4, 3, 1, 8 and 11 in an
 empty BST
                       6



                 2          8



            1          4         11



                 3
Binary Search Tree (Insert)
Try inserting 1, 2, 3, and 4 in an empty
 BST.
           1


                2



                     3



                          4
Binary Search Tree (Insert)
void BST::insert(int x){
    node *n = new node(x);
    node *tmp = root;
    if(tmp = NULL)
           root = n;
    else{
           node *tmp2;
           while(tmp!=NULL){
                      tmp2 = tmp;
                      if(x < tmp->item)
                                 tmp = tmp->left;
                      else
                                 tmp = tmp->right;
           }
           if(x < tmp2->item)
                      tmp2->left = n;
           else
                      tmp2->right = n;
    }
}
BST (Delete)
In deletion, we don’t ask for a position.
 We ask for the actual item that has to be
 deleted.                         Deleting a leaf
                     6



               2            8



                    4             11
          1

                         Deleting a node with one child
               3
                         Deleting a node with two children
Deleting a Leaf (-1)
               6



           2       8



     1         4        20



-5         3       10        50


      -1
Deleting a Node with a Child(-5)
                 6



             2       8



        1        4        20



   -5        3       10        50


        -1
Deleting a node with two
       children (2)
              6



          3
          2       8



     1        4        20



-5        3       10        50


     -1
DeleteNode Code
bool BST::deleteNode(int x){
  node *del = searchNode(x);
  if(del->left == NULL && del->right==NULL)
       delete del; //leaf
  else{

    }
}
One Child
if(del->left==NULL)
   del = del->right;
else
if(del->right==NULL)
   del = del->left;
Two Children
else{
  node *ptr = minimum(del->right);
  int x = ptr->item;
  deleteNode(x);
  del->item = x;
}
Running of Operations
Linear
          1


              2



                  3



                      4
Discussion
 We did not achieve our goal of log n.
 Can we improve?
 Always keep the tree balanced               A



                                     D                E



                                 H        I       J       L


                                     P                Q
Adelson-Velski Landis (AVL)
             Tree
An AVL tree is a binary search tree where
 every node of the tree satisfies the
 following property:
  The height of the left and right subtrees of a
   node differs by at most one.
Adelson-Velski Landis (AVL)
           Tree
Adelson-Velski Landis (AVL)
              Tree
 In order to properly implement the AVL, the node has to
   be redefined.
class node{
public:
   int item;
   node *left;
   node *right;
   int height;
   node(int x) { item = x; left = right = NULL; }
   node( ) { item = 0; left = right = NULL; }
};
Adelson-Velski Landis (AVL)
               Tree
 What kinds of violations may occur in a regular
  BST that will result in height imbalance?


1                         3              3


     2                         2     1


         3                 1                 2
Right Rotate

1
                        2

    2
                    1       3

        3
Left-Rotate

            2


        1       3
Left-Right Rotate

    3
                             2
1
                         1       3
        2
Right-Left Rotate

3           3
                            2
    2           2
                        1       3

1                   1
Challenge
Insert the following items in an AVL
  10, 20, 30, 40, 50, 60, 70, 80, 71, 61, 51, 41,
   31, 21, 11
Right Rotate
void BST::rightRotate(node *r){
  node *p = r->left;
  r->left = p->right;
  p->right = r;
  //fill in the missing code
}
Left Rotate
void BST::leftRotate(node *r){
  node *p = r->right;
  r->right= p->left;
  p->left= r;
  //fill in the missing code
}
Other Rotations
I leave this as an exercise
Insert
void BST::insert(int x){
   //do insert as in BST
   current = x;
   set current to balanced
   do{
          previous = x;
          update height of current
          lh = height of the left subtree of current
          rh = height of the left subtree of current
          set current as left leaning, right leaning, or balanced
          if(violation occurs)
                     perform corresponding rotation
   }while(??);
}

Contenu connexe

Tendances (20)

Tree in data structure
Tree in data structureTree in data structure
Tree in data structure
 
Binary Search Tree (BST)
Binary Search Tree (BST)Binary Search Tree (BST)
Binary Search Tree (BST)
 
Red black tree
Red black treeRed black tree
Red black tree
 
Search tree,Tree and binary tree and heap tree
Search tree,Tree  and binary tree and heap treeSearch tree,Tree  and binary tree and heap tree
Search tree,Tree and binary tree and heap tree
 
2 3 Trees Algorithm - Data Structure
2 3 Trees Algorithm - Data Structure2 3 Trees Algorithm - Data Structure
2 3 Trees Algorithm - Data Structure
 
Binary Tree in Data Structure
Binary Tree in Data StructureBinary Tree in Data Structure
Binary Tree in Data Structure
 
Avl trees
Avl treesAvl trees
Avl trees
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Tree - Data Structure
Tree - Data StructureTree - Data Structure
Tree - Data Structure
 
Binary tree and Binary search tree
Binary tree and Binary search treeBinary tree and Binary search tree
Binary tree and Binary search tree
 
Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures
 
2 3 tree
2 3 tree2 3 tree
2 3 tree
 
AVL Tree Data Structure
AVL Tree Data StructureAVL Tree Data Structure
AVL Tree Data Structure
 
2-3 Tree
2-3 Tree2-3 Tree
2-3 Tree
 
Binary tree traversal ppt
Binary tree traversal pptBinary tree traversal ppt
Binary tree traversal ppt
 
Terminology of tree
Terminology of treeTerminology of tree
Terminology of tree
 
Balanced Tree (AVL Tree & Red-Black Tree)
Balanced Tree (AVL Tree & Red-Black Tree)Balanced Tree (AVL Tree & Red-Black Tree)
Balanced Tree (AVL Tree & Red-Black Tree)
 
Binary tree
Binary tree Binary tree
Binary tree
 
Heaps & priority queues
Heaps & priority queuesHeaps & priority queues
Heaps & priority queues
 
Hashing Technique In Data Structures
Hashing Technique In Data StructuresHashing Technique In Data Structures
Hashing Technique In Data Structures
 

Similaire à Binary Search Tree and AVL (20)

Binary searchtrees
Binary searchtreesBinary searchtrees
Binary searchtrees
 
CS-102 BST_27_3_14v2.pdf
CS-102 BST_27_3_14v2.pdfCS-102 BST_27_3_14v2.pdf
CS-102 BST_27_3_14v2.pdf
 
Tree & bst
Tree & bstTree & bst
Tree & bst
 
Lecture7 data structure(tree)
Lecture7 data structure(tree)Lecture7 data structure(tree)
Lecture7 data structure(tree)
 
Lecture7 data structure(tree)
Lecture7 data structure(tree)Lecture7 data structure(tree)
Lecture7 data structure(tree)
 
Lecture7 data structure(tree)
Lecture7 data structure(tree)Lecture7 data structure(tree)
Lecture7 data structure(tree)
 
8 chapter4 trees_bst
8 chapter4 trees_bst8 chapter4 trees_bst
8 chapter4 trees_bst
 
Lec16
Lec16Lec16
Lec16
 
Chap 5 Tree.ppt
Chap 5 Tree.pptChap 5 Tree.ppt
Chap 5 Tree.ppt
 
CS-102 BST_27_3_14.pdf
CS-102 BST_27_3_14.pdfCS-102 BST_27_3_14.pdf
CS-102 BST_27_3_14.pdf
 
Skiena algorithm 2007 lecture05 dictionary data structure trees
Skiena algorithm 2007 lecture05 dictionary data structure treesSkiena algorithm 2007 lecture05 dictionary data structure trees
Skiena algorithm 2007 lecture05 dictionary data structure trees
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in Scala
 
Arrays and structures
Arrays and structuresArrays and structures
Arrays and structures
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Review session2
Review session2Review session2
Review session2
 
Binary Tree
Binary  TreeBinary  Tree
Binary Tree
 
Binary search trees
Binary search treesBinary search trees
Binary search trees
 
Trees
TreesTrees
Trees
 
Lecture 7-BinarySearchTrees.ppt
Lecture 7-BinarySearchTrees.pptLecture 7-BinarySearchTrees.ppt
Lecture 7-BinarySearchTrees.ppt
 
chapter5.PPT
chapter5.PPTchapter5.PPT
chapter5.PPT
 

Plus de Katang Isip

Reflection paper
Reflection paperReflection paper
Reflection paperKatang Isip
 
Punctuation tips
Punctuation tipsPunctuation tips
Punctuation tipsKatang Isip
 
Class list data structure
Class list data structureClass list data structure
Class list data structureKatang Isip
 
Hash table and heaps
Hash table and heapsHash table and heaps
Hash table and heapsKatang Isip
 

Plus de Katang Isip (7)

Reflection paper
Reflection paperReflection paper
Reflection paper
 
Punctuation tips
Punctuation tipsPunctuation tips
Punctuation tips
 
3 act story
3 act story3 act story
3 act story
 
Class list data structure
Class list data structureClass list data structure
Class list data structure
 
Stack and queue
Stack and queueStack and queue
Stack and queue
 
Hash table and heaps
Hash table and heapsHash table and heaps
Hash table and heaps
 
Time complexity
Time complexityTime complexity
Time complexity
 

Dernier

Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinojohnmickonozaleda
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 

Dernier (20)

Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipino
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 

Binary Search Tree and AVL

  • 2. Preliminaries Search Array List Stack? Queue? For large amounts of input, the linear access time of lists is prohibitive
  • 3. Preliminaries Tree A collection of nodes The collection can be empty Otherwise, the tree consists of a distinguished node r, called the root, and zero or more (sub)trees T1, T2, T3, …, Tk, each of whose roots are connected by a directed edge to r. The root of each subtree is said to be a child of r, and r is the parent of each subtree root
  • 4. Preliminaries root T1 T2 T3 T4 Tk …
  • 5. Preliminaries Tree A tree is a collection of n nodes, one of which is the root, and n-1 edges. Each edge connects some node to its parent and every node except the root has one parent
  • 6. Preliminaries ROOT A INTERNAL NODES INTERNAL NODES B C D E F G LEAF LEAF H I J L M N O LEAF LEAF LEAVES P Q LEAVES
  • 7. Binary Tree A binary tree is a tree in which no node can have more than two children root TL TR
  • 8. Binary Tree A D E H I J L P Q
  • 9. Implementation  Node class node{ public: int item; node *left; node *right; node(int x) { item = x; left = right = NULL; } node( ) { item = 0; left = right = NULL; } };
  • 10. Expression Trees (a+b*c)+((d*e+f)*g) + + * a * + g b c * f d e
  • 11. Binary Search Tree  An application of binary trees is their use in searching  Let us assume that each node in the tree is assigned a key value, and assume that this is an integer  The property that makes a binary tree into a binary search tree is that for every node, X, in the tree, the values of all keys in the left subtree are smaller than the key value in X, and the values of all keys in the right subtree are larger than the key value in X.
  • 12. Binary Search Tree 6 6 2 8 2 8 1 4 1 4 3 3 7
  • 13. Binary Search Tree class BST{ private: int size; node *root; public: BST() {size = 0; root = NULL;} void insert(int); bool delete(int); bool search(int); int minimum(); int maximum(); };
  • 14. Binary Search Tree (Search) Search for 10 6 2 8 1 4 20 3 10 50
  • 15. Binary Search Tree (Search) bool BST::search(int x){ node *tmp = root; while(tmp!=NULL){ if(x == tmp->item) return true; if(x < tmp->item) tmp = tmp->left; else tmp = tmp->right; } return false; }
  • 16. Binary Search Tree (Minimum) 6 2 8 1 4 20 -5 3 10 50 -1
  • 17. Binary Search Tree (Minimum) int BST::minimum(){ node *tmp = root; while(tmp->left != NULL) tmp = tmp -> left; return temp->item; }
  • 18. Binary Search Tree (Insert) 6 Insert 20, 10, 50 2 8 1 4 20 3 10 50
  • 19. Binary Search Tree (Insert) Let’s insert 6, 2, 4, 3, 1, 8 and 11 in an empty BST 6 2 8 1 4 11 3
  • 20. Binary Search Tree (Insert) Try inserting 1, 2, 3, and 4 in an empty BST. 1 2 3 4
  • 21. Binary Search Tree (Insert) void BST::insert(int x){ node *n = new node(x); node *tmp = root; if(tmp = NULL) root = n; else{ node *tmp2; while(tmp!=NULL){ tmp2 = tmp; if(x < tmp->item) tmp = tmp->left; else tmp = tmp->right; } if(x < tmp2->item) tmp2->left = n; else tmp2->right = n; } }
  • 22. BST (Delete) In deletion, we don’t ask for a position. We ask for the actual item that has to be deleted. Deleting a leaf 6 2 8 4 11 1 Deleting a node with one child 3 Deleting a node with two children
  • 23. Deleting a Leaf (-1) 6 2 8 1 4 20 -5 3 10 50 -1
  • 24. Deleting a Node with a Child(-5) 6 2 8 1 4 20 -5 3 10 50 -1
  • 25. Deleting a node with two children (2) 6 3 2 8 1 4 20 -5 3 10 50 -1
  • 26. DeleteNode Code bool BST::deleteNode(int x){ node *del = searchNode(x); if(del->left == NULL && del->right==NULL) delete del; //leaf else{ } }
  • 27. One Child if(del->left==NULL) del = del->right; else if(del->right==NULL) del = del->left;
  • 28. Two Children else{ node *ptr = minimum(del->right); int x = ptr->item; deleteNode(x); del->item = x; }
  • 30. Discussion  We did not achieve our goal of log n.  Can we improve?  Always keep the tree balanced A D E H I J L P Q
  • 31. Adelson-Velski Landis (AVL) Tree An AVL tree is a binary search tree where every node of the tree satisfies the following property: The height of the left and right subtrees of a node differs by at most one.
  • 33. Adelson-Velski Landis (AVL) Tree  In order to properly implement the AVL, the node has to be redefined. class node{ public: int item; node *left; node *right; int height; node(int x) { item = x; left = right = NULL; } node( ) { item = 0; left = right = NULL; } };
  • 34. Adelson-Velski Landis (AVL) Tree  What kinds of violations may occur in a regular BST that will result in height imbalance? 1 3 3 2 2 1 3 1 2
  • 35. Right Rotate 1 2 2 1 3 3
  • 36. Left-Rotate 2 1 3
  • 37. Left-Right Rotate 3 2 1 1 3 2
  • 38. Right-Left Rotate 3 3 2 2 2 1 3 1 1
  • 39. Challenge Insert the following items in an AVL 10, 20, 30, 40, 50, 60, 70, 80, 71, 61, 51, 41, 31, 21, 11
  • 40. Right Rotate void BST::rightRotate(node *r){ node *p = r->left; r->left = p->right; p->right = r; //fill in the missing code }
  • 41. Left Rotate void BST::leftRotate(node *r){ node *p = r->right; r->right= p->left; p->left= r; //fill in the missing code }
  • 42. Other Rotations I leave this as an exercise
  • 43. Insert void BST::insert(int x){ //do insert as in BST current = x; set current to balanced do{ previous = x; update height of current lh = height of the left subtree of current rh = height of the left subtree of current set current as left leaning, right leaning, or balanced if(violation occurs) perform corresponding rotation }while(??); }