CS 3013 Binary Search Trees.

Slides:



Advertisements
Similar presentations
Chapter 12 Binary Search Trees
Advertisements

Comp 122, Spring 2004 Binary Search Trees. btrees - 2 Comp 122, Spring 2004 Binary Trees  Recursive definition 1.An empty tree is a binary tree 2.A node.
S. Sudarshan Based partly on material from Fawzi Emad & Chau-Wen Tseng
Jan Binary Search Trees What is a search binary tree? Inorder search of a binary search tree Find Min & Max Predecessor and successor BST insertion.
Analysis of Algorithms CS 477/677 Binary Search Trees Instructor: George Bebis (Appendix B5.2, Chapter 12)
CS 332: Algorithms Binary Search Trees. Review: Dynamic Sets ● Next few lectures will focus on data structures rather than straight algorithms ● In particular,
David Luebke 1 5/4/2015 Binary Search Trees. David Luebke 2 5/4/2015 Dynamic Sets ● Want a data structure for dynamic sets ■ Elements have a key and satellite.
Binary Search Trees Comp 550.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
© 2006 Pearson Addison-Wesley. All rights reserved11 B-1 Chapter 11 (continued) Trees.
Universal Hashing When attempting to foil an malicious adversary, randomize the algorithm Universal hashing: pick a hash function randomly when the algorithm.
1.1 Data Structure and Algorithm Lecture 12 Binary Search Trees Topics Reference: Introduction to Algorithm by Cormen Chapter 13: Binary Search Trees.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
David Luebke 1 7/2/2015 ITCS 6114 Binary Search Trees.
David Luebke 1 7/2/2015 Medians and Order Statistics Structures for Dynamic Sets.
Marc Smith and Jim Ten Eyck
CS 2133: Data Structures Binary Search Trees.
David Luebke 1 9/18/2015 CS 332: Algorithms Red-Black Trees.
Chapter 12. Binary Search Trees. Search Trees Data structures that support many dynamic-set operations. Can be used both as a dictionary and as a priority.
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
Tree (new ADT) Terminology:  A tree is a collection of elements (nodes)  Each node may have 0 or more successors (called children)  How many does a.
Binary SearchTrees [CLRS] – Chap 12. What is a binary tree ? A binary tree is a linked data structure in which each node is an object that contains following.
Binary Search Tree Qamar Abbas.
Red-Black Trees. Review: Binary Search Trees ● Binary Search Trees (BSTs) are an important data structure for dynamic sets ● In addition to satellite.
Binary Search Trees (BST)
Lecture 19. Binary Search Tree 1. Recap Tree is a non linear data structure to present data in hierarchical form. It is also called acyclic data structure.
Trees Chapter 10. CS 308 2Chapter Trees Preview: Preview: The data organizations presented in previous chapters are linear, in that items are one.
Mudasser Naseer 1 1/25/2016 CS 332: Algorithms Lecture # 10 Medians and Order Statistics Structures for Dynamic Sets.
CS6045: Advanced Algorithms Data Structures. Dynamic Sets Next few lectures will focus on data structures rather than straight algorithms In particular,
DS.T.1 Trees Chapter 4 Overview Tree Concepts Traversals Binary Trees Binary Search Trees AVL Trees Splay Trees B-Trees.
Binary Search Trees What is a binary search tree?
Non Linear Data Structure
Trees Chapter 15.
CSCE 3110 Data Structures & Algorithm Analysis
CSCE 3110 Data Structures & Algorithm Analysis
Tree.
Trees Chapter 11 (continued)
Trees Chapter 11 (continued)
CS 3013 Binary Search Trees.
UNIT III TREES.
CS 332: Algorithms Red-Black Trees David Luebke /20/2018.
Binary Search Tree (BST)
CS 302 Data Structures Trees.
Binary Search Tree Chapter 10.
Lecture 22 Binary Search Trees Chapter 10 of textbook
Data Structures & Algorithm Design
abstract containers sequence/linear (1 to 1) hierarchical (1 to many)
CSC 172– Data Structures and Algorithms
CS200: Algorithms Analysis
ITEC 2620M Introduction to Data Structures
Lecture 7 Algorithm Analysis
Binary Trees, Binary Search Trees
Binary Search Trees.
Ch. 11 Trees 사실을 많이 아는 것 보다는 이론적 틀이 중요하고, 기억력보다는 생각하는 법이 더 중요하다.
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
Find in a linked list? first last 7  4  3  8 NULL
Chapter 16 Tree Implementations
Lecture 7 Algorithm Analysis
Chapter 12: Binary Search Trees
CS6045: Advanced Algorithms
Lecture 7 Algorithm Analysis
Binary Trees, Binary Search Trees
Trees Chapter 10.
Binary Search Trees Comp 122, Spring 2004.
Binary Trees, Binary Search Trees
Chapter 11 Trees © 2011 Pearson Addison-Wesley. All rights reserved.
Tree (new ADT) Terminology: A tree is a collection of elements (nodes)
Presentation transcript:

CS 3013 Binary Search Trees

Definition of a Tree A Binary tree is a set T of nodes such that either 1. T is empty or 2. T is partitioned into three disjoint subsets. A single node r, the root Two (possibly empty) sets that are binary trees, called left and right subtrees of r. T T T Tl Tr

Structure of a Tree root struct Node{ int value; Node * left; Node * right; } 5 class Tree{ Node * root; public: Tree();//constructor Insert(int); Print(); } 4 6 3 10 7 9

Binary Search Trees Binary Search Trees (BSTs) are an important data structure for manipulating dynamically changing data sets. Each node has the following fields: value: an identifying field inducing a total ordering left: pointer to a left child (may be NULL) right: pointer to a right child (may be NULL) p: (sometimes) pointer to a parent node (NULL for root)

Binary Search Trees BST property: Value of nodes in left subtree <= roots value Value of nodes in right subtree > roots value Example: F B H K D A

Inorder Tree Walk What does the following code do? TreeWalk(x) TreeWalk(left[x]); print(x); TreeWalk(right[x]); A: prints elements in sorted (increasing) order This is called an inorder tree walk Preorder tree walk: print root, then left, then right Postorder tree walk: print left, then right, then root

Inorder Tree Walk Example: How long will a tree walk take? Prove that inorder walk prints in monotonically increasing order F B H K D A

Operations on BSTs: Search Given a key and a pointer to a node, returns an element with that key or NULL: Node * TreeSearch(Node * ptr,int k){ if (ptr == NULL)return NULL; if (ptr->value==k) return ptr; if (k < ptr->value) return TreeSearch(ptr->left, k); else return TreeSearch(ptr->right, k); }

BST Search: Example Search for D and C: F B H K D A

Operations of BSTs: Insert For a non recursive insert Adds an element x to the tree so that the binary search tree property continues to hold The basic algorithm Like the search procedure above Insert x in place of nullptr Use a “trailing pointer” to keep track of where you came from (like inserting into singly linked list)

BST Insert: Example Example: Insert C F B H K D A C

BST class BST class { Node * _tree; public: BST(){ _tree=nullptr;} ~BST();// Destructor Insert(int v){AuxInsert(_tree,v);} AuxInsert(Node* & , const int & ) }

Recursive Insert in a Class void BST::InsertAux(Node* & locptr, const int & item) {if(locptr==nullptr) locptr=new Node(item); else if (item < locptr->value) InsertAux(locptr->left, item); InsertAux(locptr->right, item); } Note &

BST Search/Insert: Running Time What is the running time of TreeSearch() or insertAux()? A: O(h), where h = height of tree What is the height of a binary search tree? A: worst case: h = O(n) when tree is just a linear string of left or right children We’ll keep all analysis in terms of h for now Later we’ll see how to maintain h = O(lg n)

BST Destroy the tree BST::~BST(){destroyTree(root)} Void BST::destroyTree(Node *& treePrt) { if (tree{treePtr != nullptr;) { destroyTree(treePtr->leftChildPtr); destroyTree(treePtr->rightChildPtr); delete treePtr; treePtr=nullptr; }

BST Operations: Delete Deletion is a bit tricky 3 cases: x has no children: Remove x x has one child: Splice out x x has two children: Swap x with successor Perform case 1 or 2 to delete it F B H K D A C Example: delete K or H or B

Delete Algorithm void TreeDelete(Node *& root, int x) { if(root!=NULL){ if(x<root->val)TreeDelete(root->left, x); else if(x>root->val)TreeDelete(root->right, x); else { // we have found it so lets delete it // tree points at it right!? // If No children we just delete it if(root->left==NULL && root->right==NULL){ delete(root); root=NULL; return; }

Delete Continued with one child // Check to see if the node to delete has only one child if(root->left==NULL){ // Then splice in the right side tree_ptr=root->right; delete root; root=tree_ptr; }else if (root->right==NULL){ // splice left tree_ptr=root->left; delete(root); } else // both children exist! so...

Delete Continued with two children // Here root has two children // We first find the successor { tempPtr=root->right; // Go right // and the all the way to the left while(tempPtr->left!=NULL){ predPtr=tempPtr; tempPtr=tempPtr->left; } root->val=tempPtr->val; // Copy the value up to the node if(root->right==tempPtr)root->right=tempPtr->right; else predPtr->left=tempPtr->right; delete tempPtr; root pred temp

BST Operations: Delete Why will case 2 always go to case 0 or case 1? A: because when x has 2 children, its successor is the minimum in its right subtree Could we swap x with predecessor instead of successor? A: yes. Would it be a good idea? A:See the Eppinger paper!!

Sorting With Binary Search Trees Informal code for sorting array A of length n: BSTSort(A) for i=1 to n TreeInsert(A[i]); InorderTreeWalk(root); What will be the running time in the Worst case? Average case?

Left Child Right Sibling Representation K D A C F B H A D H C RCLS format Normal format Really is a binary way to represent an n ary tree. Also each child has a pointer to its parent.

Recursive Traversal of a LCRS Tree Traverse(t) { if (t != NULL) then Traverse(t.child()) If (t.sibling() !=NULL) then Traverse(t.sibling()) } B H A D H C

Algorithm BT->LCRS Format Can you design an algorithm that will convert a binary tree to the left child right sibling format?

Saving a binary search tree in a file We can do this so the tree gets restored to the original shape. How do we do this? save in preorder ! Or we can restore it in a balanced shape save in inorder and ?

Loading a balanced tree from a sorted list readTree(Node *& treePtr,int n) { if (n>0) { // read in the left subtree treePtr=new Node(NULL,NULL); readTree(treePtr->left,n/2); cin>> treePtr->val; // read in the right subtree readTree(treePtr->right,(n-1)/2); }

Level Order Traversal F B H K D A How do you perform an level by level traversal? F B H K D A Q.enq(root) While(Q not empty){ x = Q.deq(); Print x; Q.enq(left_child); Q.enq(right_child); } NOTE: This uses a queue as its support data structure

Huffman Codes Variable length coding schemes. These schemes represent characters that occur more frequently with shorter codes. We thus attempt to minimize the expected length of the code for the character. Expected length = The weights represent the probability of occurrence of the character within the coded string. It is a value between 0 and 1.

Constructing the Code 1. Initialize a list of one-node binary trees containing the weights of each char 2. Do the following n-1 times Find two trees T’ and T’’ in this list with minimal weight Replace these two trees with a binary tree whose root is w’+w’’, and label the pointers to these trees with 0 and 1 W’+w’’ 1 T’’ T’

Example Construction 1 Also,this is Immediately Decodable! A=00 B=01 1.0 1 Also,this is Immediately Decodable! A=00 B=01 C=10 D=110 E=1110 F=1111 .40 1 .20 1 .60 .10 1 1 .35 .25 .20 .10 .08 .02 A B C D E F

Expression Trees + * + + X 3 Y W 5 W + 5 * X + 3 + Y inorder traversal ((W+5)*X + (3+Y)) with parens How about preorder and postorder traversals?

Problem A preorder traversal of a binary tree produced ADFGHKLPQRWZ and an inorder traversal produced GFHKDLAWRQPZ Draw the binary tree.

Program to Build Tree substr(start, len) 0 1 2 . . . void BuildTree(string in,string post) { char root; int len=in.length(); // NOTE: Last char of postorder traveral is the root of the tree if(len==0)return; root=post[len-1]; cout<<root; // print the root // Search for root in the inorder traversal list int i=0; while(in[i]!=root)i++; // skip to the root // i now points to the root in the inorder traversal // The chars from 0 to i-1 are in the left subtree and // the chars from i+1 to len_in-1 are in the right sub tree. // Process left sub tree BuildTree(in.substr(0,i),post.substr(0,i)); //Process right sub tree BuildTree(in.substr(i+1,len-i-1), post.substr(i,len-i-1)); } 0 1 2 . . . substr(start, len)