


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Finding a value in a binary tree potentially means visiting every node. • Searching a sorted array would still be faster (via binary search).
Typology: Schemes and Mind Maps
1 / 4
This page cannot be seen from the preview
Don't miss anything!



3/9/ X-
3/9/ X-
3/9/00 (^) X-
3/9/00 (^) X-
3/9/ X-
12
15
14
12
15
14
3/9/ X-
12
15
14
12
15
14
NULL
3/9/ X-
Code For Finding an Item
bool find (BTreeNode *root, int item) { if ( root == NULL ) return false; else if (item == root->data) return true; else if (item < root->data) return find (root->left, item); else return find (root->right, item); }
3/9/ X-
Running time of BST find
12
15
10
3/9/00 (^) X-
Running time of find (2)
12
15
18
3/9/00 (^) X-
Inserting in a BST
To insert a new key:
3/9/ X-
Example
3/9/ X-
Code For Inserting in a BST
// Add data to tree void insert (BTreeNode * & root, int data) { if ( root == NULL ) { root = new BTreeNode; root->left = NULL; root->right = NULL; root->item = data; return; } if (data < root->item) insert (root->left, data); if (data > root->item ) insert (root->right, data); }
3/9/ X-
Deletion (4): Deleting the Node
void deleteNode (BTreeNode&t) { if (t->left && t->right) { // 2 children t->data = findMin (t->right); deleteItem (t->data, t->right); } else { // 0 or 1 child BTreeNode oldVal = t; if (t->left) // left child only t = t->left; else if (t->right) // right child only t = t->right; else // no children t = NULL; delete oldVal; //delete this node } } 3/9/ X-
Deletion (5): Finding Min
// PRECONDITION: t is non-NULL int findMin (BTreeNode* t) { assert(t != NULL); while (t->left != NULL) t = t->left; return t->data; }
3/9/00 (^) X-
Magic Trick
Preview of CSE326/373:
Balanced Search Trees
3/9/ X-
BST Summary