data structure & algorithm 09 – binary search tree jjcao
TRANSCRIPT
2
Dictionary ADT
• U = Universe of possible keys• K U - Set of keys actually handled
Operations: - Search(key) - Insert(x) - Delete(x)
• Possible implementations: Linked list, BST, Array, Hash table
3
Priority Queue ADT
Priority Queue – a set of elements S, each with a key:
• insert(S,x) - insert element x into S S <- S U {x}
• max(S) - return element of S with largest key
• extract-max(S) - remove and return element of S with largest key
• Possible implementations: Heap
5
(Binary) Search Trees ADT
Operations:• Initialize - the data structure
• Search - For an element with a given key• Insert - a new element• Delete - a specified element
• Predecessor - return element with closest smaller key• Successor - return element with closest larger key• Join – combine two dictionaries to make a larger one• PrintSorted - print the dictionary in sorted order
• Minimum - return the element with smallest key• Maximum - return the element with largest key
Dictionary
7
Binary Search Trees
• Different binary search trees can represent the same set of values. • The worst-case running time for most search-tree operations is
proportional to the height of the tree. • (a) A binary search tree on 6 nodes with height 2. (b) A less
efficient binary search tree with height 4 that contains the same keys.
8
class Node{int m_key; //data item (key)double m_data; //data item
Node* m_leftChild; //this node’s left childNode* m_rightChild; //this node’s right child};
class Tree{private:Node* pRoot; //first node of tree
public:Tree() : pRoot(NULL) { }
Node* search(int key) { /*body not shown*/ }Node* min(int key) ) { /*body not shown*/ }…};
…};
Array is not work here since it may be incomplete.
17
Randomly built binary search trees
Theorem:If we insert n random elements into an initially empty Binary Search Tree, then the average node depth is O(lgn)
Assume:• Trees are formed by insertions only• All input permutations are equally
likely
23
Balanced Trees: 2-3-4 Trees
• 2-nodes – as in a BST – hold 1 key and two children
• 3-nodes hold 2 keys and have 3 links to children• 4-nodes hold 3 keys and have 4 links to children
24
Insert
• Do an unsuccessful search• if search terminated at a 2-node,
turn it into a 3-node• if search terminated in a 3-node, turn
it into a 4-node• if search terminates at a 4-node,– split 4-node into one 2-node and one 3-
node– pass one key back up to its parent
26
Properties of n node 2-3-4 trees
Property 1:Worst-case Search takes O(log n) time
Property 2:• Worst-case for Insert makes O(log n)
splits• Average-case Insert seems to be < 1 split