Data Structure Chapter 5. Binary Trees
|
|
- Bertina Dean
- 6 years ago
- Views:
Transcription
1 ata Structure hapter 5 Binary Trees r. Patrick han School of omputer Science and Engineering South hina University of Technology Outline Recursion (h.4) Binary Trees (h 5) Introduction (h 5.) Traversal (h 5.) Implementation (h 5.) Binary Search Trees (h 5.4) Priority Queues and Heaps (h 5.5) Huffman oding Trees (h 5.6)
2 Recursion A recursion is a procedure which calls itself The recursive procedure call must use different arguments from the original one Otherwise the procedure would always get into an infinite loop Recursion ans = 4 Example: Factorial function n! = n (n-) f ( n) = n f ( n ) if n = else 4 * factorial() factorial()=6 * factorial() factorial()= * factorial() factorial()= factorial(4) factorial() factorial() int factorial(int n) { if (n == ) return ; else return n * factorial(n-); * factorial() factorial()= factorial() factorial() 4
3 Recursion int factorial(int n) { if (n == ) return ; else return n * factorial(n-); factorial(4) factorial() factorial() factorial() factorial() Recursive all alls to the current method Each recursive call should be defined so that it makes progress towards a base case Base ase Values of the input variables for which we perform no recursive calls are called base cases At least one base case Every possible chain of recursive calls must eventually reach a base case 5 Recursion Example has two Recursive alls p( x, n) = x p( x,( n ) / ) p( x, n / ) if x= if x> is odd if x> is even 4 = (4/)* = ( 4/ ) = ( ) = 4 = 6 5 = +(4/)* = ( 4/ ) = ( ) = (4 ) = 6 = (6/ )* = ( 6/ ) = ( ) = 8 = 64 = +(6/)* = ( 6/ ) = ( ) = (8 ) = 8 int power(int x, int n) { if (n == ) return ; if (n % == ) { y = Power(x, (n - )/); return x * y * y; else { y = Power(x, n/); return y y; Base ase Recursive all It is important that we used a variable twice here rather than calling the method twice 6
4 Recursion Tower of Hanoi A B Recursion: Tower of Hanoi More than steps Break own Recursive all More than steps More than steps Recursive all step 8
5 Recursion: Tower of Hanoi More than steps Break own Recursive all More than steps More than steps Recursive all step 9 Recursion: Tower of Hanoi More than steps Break own Base ase Base ase step step step
6 Recursion: Tower of Hanoi The solution Recursion: Tower of Hanoi Solution: void solvetowers(int count, char source, char destination, char spare) { if (count == ) { cout << "Move top disk from pole " << source << " to pole " << destination); else { solvetowers(count-, source, spare, destination); // Left solvetowers(, source, destination, spare); // step solvetowers(count-, spare, destination, source); // Right // end if // end solvetowers
7 Recursion: Observation : Same Algorithm Break down the problem into smaller parts and eventually reach a base case Binary Tree: Introduction A binary tree is made up of a finite set of nodes that is either empty or consists of a node called the root together with two binary trees which are disjoint from each other and from the root A B E F H G I J 4
8 Binary Tree: Introduction Root epth: Level: Parent of V R Ancestors of V Internal Node epth: Level: epth: Level: epth: Level: Sibling of V H Subtree rooted at V P G V F B Edge Leaf Node escendants of V epth: 4 Level: 4 Height is 5 hildren of V J 5 Binary Tree Full binary tree Each node being either Leaf Internal node with exactly two non-empty children B F A E H B B A E H F G A 6
9 Binary Tree A omplete binary tree If the height of the tree is d, then all levels except possibly level d- are completely full The bottom level has all nodes filled in from the left side A T A B B H E H E T J I G Binary Tree Full Binary Tree Theorem Theorem The number of leaves in a non-empty full binary tree is one more than the number of internal nodes A H E A Leaves 4 Internal Nodes T B B F E H G Leaves 5 Internal Nodes 4 I H 8
10 Binary Tree Full Binary Tree Theorem Theorem The number of null pointers in a non-empty binary tree is one more than the number of nodes in the tree A H E A T B Leaves 4 Internal Nodes Null Pointers Nodes 4 x = = B F E H G H Leaves 5 Internal Nodes 4 Null Pointers Nodes 5 x = = 9 I 9 Binary Tree: Node AT Template <class Elem> class BinNode { public: virtual Elem& val( ) =; virtual BinNode* left( ) const = ; virtual BinNode* right( ) const = ; virtual void setval( const Elem& ) = ; virtual void setleft( BinNode* ) = ; virtual void setright( BinNode* ) = ; virtual bool isleaf( ) = ; B A E H F G I J
11 Binary Tree: Node // Binary tree node class template <class Elem> class BinNodePtr : public BinNode<Elem> { private: Elem it; // The node's value BinNodePtr* lc; // Pointer to left child BinNodePtr* rc; // Pointer to right child public: BinNodePtr() { lc = rc = ; BinNodePtr(Elem e, BinNodePtr* l=, BinNodePtr* r=) { it = e; lc = l; rc = r; Elem& val() { return it; void setval(const Elem& e) { it = e; inline BinNode<Elem>* left() const { return lc; void setleft(binnode<elem>* b) { lc = (BinNodePtr*)b; inline BinNode<Elem>* right() const { return rc; void setright(binnode<elem>* b) { rc = (BinNodePtr*)b; BinNodePtr anode(); bool isleaf() { return (lc == ) && (rc == ); ; Binary Tree: Traversals Traversal is a process for visiting the nodes in some order Any traversal that lists every node in the tree exactly once is called an enumeration of the tree s nodes A B E H F G I J
12 Binary Tree: Traversals Preorder traversal Visit each node before visiting its children A B E F G H I J Postorder traversal Visit each node after visiting its children B F G E J I H A Inorder traversal Visit the left subtree, then the node, then the right subtree B A F E G I J H A B E H F G I J Binary Tree: Traversals Preorder traversal Visit each node before visiting its children Postorder traversal Visit each node after visiting its children Inorder traversal Visit the left subtree, then the node, then the right subtree template <class Elem> void preorder(binnode<elem>* subroot) { if (subroot == ) return; // Empty visit(subroot); // Perform some actions preorder(subroot->left()); // left preorder(subroot->right()); // right template <class Elem> void postorder(binnode<elem>* subroot) { if (subroot == ) return; // Empty postorder(subroot->left()); // left postorder(subroot->right()); // right visit(subroot); // Perform some actions template <class Elem> void inorder(binnode<elem>* subroot) { if (subroot == ) return; // Empty inorder(subroot->left()); // left visit(subroot); // Perform some actions inorder(subroot->right()); // right 4
13 Binary Tree: Traversals Which one is better? B A () template <class Elem> void preorder(binnode<elem>* subroot) { if (subroot == ) return; // Empty F visit(subroot); // Perform some action preorder(subroot->lc()); preorder(subroot->rc()); check if the tree is empty at first E H G I J () template <class Elem> void preorder(binnode<elem>* subroot) { visit(subroot); // Perform some action if (subroot->left()!= ) preorder(subroot->lc()); if (subroot->right()!= ) preorder(subroot->rc()); check if the right and left point are empty 5 Binary Tree: Traversals Which one is better? Advantage of ase Reduce half recursive calls (refer to Theorem in slide 9) Advantage of ase Only one base case checking For complex traversals, checking criteria may be very complicated Avoid the bugs E.g. the initial call passes an empty tree ase should be used B A E H F G I J 6
14 Binary Tree ifferent Leafs & Internal Nodes Each node stores the same kind of data A Internal nodes and leaves store different types of data - B * c F * + G H 4 x * a x 4x(x+a) -c Binary Tree ifferent Leafs & Internal Nodes Three implementation methods Union Inheritance Inheritance with virtual function 8
15 Binary Tree: ifferent Leafs & Internal Nodes Union Implementation enum Nodetype {leaf, internal; class VarBinNode { // Generic node class public: Nodetype mytype; // Store type for node union { struct { // Internal node VarBinNode* left; // Left child VarBinNode* right; // Right child Operator opx; // Value intl; Operand var; ; // Leaf constructor VarBinNode(const Operand& val) { mytype = leaf; var = val; // Internal node constructor // Leaf: Value only Indicate if it is an internal node or a leaf Two types of information Two different constructor VarBinNode(const Operator& op, VarBinNode* l, VarBinNode* r) { mytype = internal; intl.opx = op; intl.left = l; intl.right = r; bool isleaf() { return mytype == leaf; VarBinNode* leftchild() { return intl.left; VarBinNode* rightchild() { return intl.right; ; 9 Binary Tree: ifferent Leafs & Internal Nodes Union Implementation // Preorder traversal void traverse(varbinnode* subroot) { if (subroot == ) return; if (subroot->isleaf()) cout << "Leaf: << subroot->var << "endl"; else { cout << "Internal: << subroot->intl.opx << "endl"; traverse(subroot->leftchild()); traverse(subroot->rightchild()); isadvantage A node is total sizes for leaf and internal node
16 Binary Tree: ifferent Leafs & Internal Nodes Inheritance Implementation class VarBinNode { // Abstract base class public: virtual bool isleaf() = ; ; class LeafNode : public VarBinNode { // Leaf private: Operand var; // Operand value public: LeafNode(const Operand& val) { var = val; // onstructor bool isleaf() { return true; Operand value() { return var; ; class IntlNode : public VarBinNode { // Internal node private: VarBinNode* left; // Left child VarBinNode* right; // Right child Operator opx; // Operator value public: IntlNode(const Operator& op, VarBinNode* l, VarBinNode* r) { opx = op; left = l; right = r; bool isleaf() { return false; VarBinNode* leftchild() { return left; VarBinNode* rightchild() { return right; Operator value() { return opx; ; Binary Tree: ifferent Leafs & Internal Nodes Inheritance Implementation void traverse(varbinnode *subroot) { // Preorder traversal if (subroot == ) return; // Empty if (subroot->isleaf()) // o leaf node cout << "Leaf: " << ((LeafNode *)subroot)->value() << endl; else { // o internal node cout << "Internal: " << ((IntlNode *)subroot)->value() << endl; traverse(((intlnode *)subroot)->leftchild()); traverse(((intlnode *)subroot)->rightchild()); isadvantage The traverse is still complicated (if-then-else is used)
17 Binary Tree: ifferent Leafs & Internal Nodes Inheritance with virtual function class VarBinNode { // Abstract base class public: virtual bool isleaf() = ; virtual void trav() = ; ; class LeafNode : public VarBinNode { // Leaf private: Operand var; // Operand value public: LeafNode(const Operand& val) { var = val; // onstructor bool isleaf() { return true; Operand value() { return var; void trav() { cout << "Leaf: " << value() << endl; ; Binary Tree: ifferent Leafs & Internal Nodes Inheritance with virtual function class IntlNode : public VarBinNode { private: VarBinNode* lc; // Left child VarBinNode* rc; // Right child Operator opx; // Operator value public: IntlNode(const Operator& op, VarBinNode* l, VarBinNode* r) { opx = op; lc = l; rc = r; bool isleaf() { return false; VarBinNode* left() { return lc; VarBinNode* right() { return rc; Operator value() { return opx; void trav() { cout << "Internal: " << value() << endl; if (left()!= ) left()->trav(); if (right()!= ) right()->trav(); ; 4
18 Binary Tree: ifferent Leafs & Internal Nodes Inheritance with virtual function // Preorder traversal void traverse(varbinnode *root) { if (root!= ) root->trav(); omparisons Inheritance Implementation Easily to add new methods to the tree class that traverse the tree Inheritance with virtual function More preferred if the internal behavior of the nodes should be hided 5 Binary Tree Space Requirements Overhead Space Amount of space necessary to maintain the data structure i.e any space not used to store the data records Overhead Fraction Amount of overhead space divided by amount of total space used 6
19 Binary Tree Space Requirements Example Full tree with all nodes are the same (two pointers to children and one element): Total space required: n(p + d) n: number of nodes p: the amount of space required by a pointer d: the amount of space required by a data value Overhead Space: pn Overhead Fraction: p / (p + d) If p = d, it means / of total space is taken up in overhead Small Quiz!!!! Q. Write a recursive function that returns the height of a binary tree template <class Elem> int findheight(binnode<elem>* subroot){... if (subroot == ) return ; // Empty subtree return + max(height(subroot->left()), height(subroot->right())); A B E H F G 8
20 Small Quiz!!!! Q. Write a recursive function that search value K in a binary tree. The function returns true if value K is exist template <class Key, class Elem, class KEomp> bool search(binnode<elem>* subroot, Key K){... if (subroot == ) return false; if (subroot->value() == K) return true; elseif (search(subroot->left())) return true; else return search(subroot->right()); B A E H F G 9 Binary Search Trees Binary Search Tree (BST) is a special case of Binary Tree All elements stored in the left subtree of a node with value K have values < K All elements stored in the right subtree of a node with value K have values >= K
21 Binary Search Trees: AT // BST implementation for the ictionary AT template <class Key, class Elem, class KEomp, class EEomp> class BST : public ictionary<key, Elem,KEomp, EEomp> { private: BinNode<Elem>* root; // Root of the BST int nodecount; // Number of nodes void clearhelp(binnode<elem>*); BinNode<Elem>* inserthelp(binnode<elem>*, const Elem&); BinNode<Elem>* deletemin(binnode<elem>*,binnode<elem>*&); BinNode<Elem>* removehelp (BinNode<Elem>*,const Key&,BinNode<Elem>*&); bool findhelp(binnode<elem>*, const Key&,Elem&) const; void printhelp(binnode<elem>*, int) const; public: BST() { root = ; nodecount = ; ~BST() { clearhelp(root); void clear() { clearhelp(root); root = ; nodecount = ; 4 Binary Search Trees: AT bool insert(const Elem& e) { root = inserthelp(root, e); nodecount++; return true; bool remove(const Key& K, Elem& e) { BinNode<Elem>* t = ; root = removehelp(root, K, t); if (t == ) return false; e = t->val(); nodecount; delete t; return true; 4
22 Binary Search Trees: AT bool removeany(elem& e) { // elete min value if (root == ) return false; // Empty BinNode<Elem>* t; root = deletemin(root, t); e = t->val(); delete t; nodecount; return true; bool find(const Key& K, Elem& e) const { return findhelp(root, K, e); int size() { return nodecount; void print() const { if (root == ) cout << "The BST is empty.\n"; else printhelp(root, ); 4 Binary Search Trees: AT inserthelp function template <class Key, class Elem, class KEomp, class EEomp> BinNode<Elem>* BST<Key,Elem,KEomp,EEomp>:: inserthelp( BinNode<Elem>* subroot, const Elem& val ) { root if (subroot == ) // Empty: create node return new BinNodePtr<Elem>(val,,); if (EEomp::lt(val, subroot->val())) subroot->setleft(inserthelp(subroot->left(), val)); else subroot->setright(inserthelp(subroot->right(), val)); return subroot; // Return subtree with node inserted subtree= B R R Return bool insert(const Elem& e) { root = inserthelp(root, e); nodecount++; return true; Base ase root=inserthelp(root,); root Recursive all Recursive all 44
23 Binary Search Trees: AT inserthelp function template <class Key, class Elem, class KEomp, class EEomp> BinNode<Elem>* BST<Key,Elem,KEomp,EEomp>:: inserthelp( BinNode<Elem>* subroot, const Elem& val ) { root root if (subroot == ) // Empty: create node return new BinNodePtr<Elem>(val,,); if (EEomp::lt(val, subroot->val())) subroot->setleft(inserthelp(subroot->left(), val)); else subroot->setright(inserthelp(subroot->right(), val)); return subroot; // Return subtree with node inserted subtree= subtree= B R R Return.L B R R Return root=inserthelp(root,); root=inserthelp(root,); bool insert(const Elem& e) { root = inserthelp(root, e); nodecount++; return true; Base ase root Recursive all Recursive all 45 Binary Search Trees: AT inserthelp function template <class Key, class Elem, class KEomp, class EEomp> BinNode<Elem>* BST<Key,Elem,KEomp,EEomp>:: inserthelp( BinNode<Elem>* subroot, const Elem& val ) { root root if (subroot == ) // Empty: create node return new BinNodePtr<Elem>(val,,); if (EEomp::lt(val, subroot->val())) subroot->setleft(inserthelp(subroot->left(), val)); else subroot->setright(inserthelp(subroot->right(), val)); return subroot; // Return subtree with node inserted subtree= B R R Return.L subtree= B R R Return root=inserthelp(root,); root=inserthelp(root,); root=inserthelp(root,9);.r 9 subtree= B R R Return bool insert(const Elem& e) { root = inserthelp(root, e); nodecount++; return true; Base ase root Recursive all Recursive all 9 46
24 Binary Search Trees: AT deletemin function template <class Key, class Elem, class KEomp, class EEomp> BinNode<Elem>* BST<Key, Elem, KEomp, EEomp>:: deletemin(binnode<elem>* subroot, BinNode<Elem>*& min) { if (subroot->left() == ) { root min = subroot; return subroot->right(); else { root Base ase // ontinue left subroot->setleft( deletemin(subroot->left(), min)); return subroot; subtree= subtree= B R.L.R (9) B R Recursive all root=deletemin(root,amin); amin root 9 4 bool remove(const Key& K, Elem& e) { BinNode<Elem>* t = ; Binary Search Trees: AT root = removehelp(root, K, t); if (t == ) return false; e = t->val(); nodecount; delete t; removehelp function return true; template <class Key, class Elem, class KEomp, class EEomp> BinNode<Elem>* BST<Key,Elem,KEomp,EEomp>:: removehelp(binnode<elem>* subroot, const Key& K, BinNode<Elem>*& t) { if (subroot == ) return ; annot find the target else if (KEomp::lt(K, subroot->val())) Searching subroot->setleft(removehelp(subroot->left(), K, t)); else if (KEomp::gt(K, subroot->val())) 99 subroot->setright(removehelp(subroot->right(), K, t)); else { // Found it: remove it Found the target BinNode<Elem>* temp; subroot 4 t = subroot; if (subroot->left() == ) te = subroot = subroot->right(); t (abnode) else if (subroot->right() == ) 4 subroot = subroot->left(); else { // Both children are non-empty subroot->setright(deletemin(subroot->right(), temp)); Elem te = subroot->val(); subroot->setval(temp->val()); temp->setval(te); t = temp; return subroot; root root root=removehelp(root,,abnode); Left Right Bingo! 99.L 4 Left Right Bingo! 4.L temp Left Right Bingo! 5 48
25 Binary Search Trees: AT removehelp function No Left hild No Right hild Have both hildren Binary Search Trees: AT clearhelp functions void clear() { clearhelp(root); root = ; nodecount = ; template <class Key, class Elem, class KEomp, class EEomp> void BST<Key,Elem,KEomp,EEomp>:: clearhelp(binnode<elem>* subroot) { if (subroot == ) return; clearhelp(subroot->left()); clearhelp(subroot->right()); delete subroot; clearhelp(root); elete the node Base ase Recursive all Recursive all root 8 9 5
26 Binary Search Trees: AT printhelp functions template <class Key, class Elem, class KEomp, class EEomp> void BST<Key,Elem,KEomp,EEomp>:: printhelp(binnode<elem>* subroot, int level) { if (subroot == ) return ; printhelp(subroot->left(), level+); for (int i=; i<level; i++) cout << ; cout << subroot->val() << \n ; printhelp(subroot->right(), level+); printhelp(root, ); Base ase Recursive all Print the node Recursive all root Small Quiz!!!! Q. raw the BST that results from each of the following commands: abst abst.insert(); abst.removeany(temp); abst.removeany(temp); abst.remove(45, temp); abst.remove(6, temp); abst.remove(9, temp); abst.remove(64, temp); abst.print(); 5
27 Small Quiz!!!! abst.insert(); abst.removeany(temp); abst.removeany(temp); abst.remove(45, temp); abst.remove(6, temp); abst.remove(9, temp); abst.remove(64, temp); abst.print(); Binary Search Trees: AT ost of BST Operations Assume d = depth of the tree Find:Θ(d) Insert: Θ(d) elete: Θ(d) d is Θ(log n) if tree is balanced The worst case: Θ(n) The average case:θ(log n)
28 Binary Tree Array-Based omplete BT Simple and compact array implementation approach for complete binary tree No overhead space omplete binary Tree is useful: Heap data structure External sorting algorithm A B H E T J I G 55 Binary Tree Array-Based omplete BT Parent(r) = (r - ) / if r and r < n Leftchild(r) = r + if r+ < n Rightchild(r) = r + if r + < n Leftsibling(r) = r - if r is even, r > and r < n Rightsibling(r) = r + if r is odd, r + < n 8 9 Position Parent Left hild 5 9 Right hild Left Sibling 5 9 Right Sibling
29 Heaps Heap is a data structure with the following properties: omplete Binary Tree Value stored in a heap are partially ordered There is a relationship between the value stored at any node and values of its children Two types of heaps Min-heap: All values less than or equal to child values Max-heap: All values greater than or equal to child values Heap can be implemented simply by using the array-based complete binary tree 5 Heaps Max-heap Min-heap
30 Heaps: AT template<class Elem,class omp> class maxheap{ private: Elem* Heap; // Pointer to the heap array int size; // Maximum size of the heap int n; // Number of elems now in heap void siftdown(int); // Put element in place public: maxheap(elem* h, int num, int max); int heapsize() const; bool isleaf(int pos) const; int leftchild(int pos) const; int rightchild(int pos) const; int parent(int pos) const; bool insert(const Elem&); bool removemax(elem&); bool remove(int, Elem&); void buildheap(); ; 59 Heaps buildheap function public void buildheap() // Heapify contents { for (int i=n/-; i>=; i) siftdown(i); on t need to call siftdown on leaf nodes template <class Elem, class omp> void maxheap<elem,omp>::siftdown(int pos) { while (!isleaf(pos)) { aheap.buildheap(); aheap.siftdown(); int j = leftchild(pos); aheap.siftdown(); int rc = rightchild(pos); aheap.siftdown(); if ((rc<n) && omp::lt(heap[j],heap[rc])) j = rc; if (!omp::lt(heap[pos], Heap[j])) return; swap(heap, pos, j); pos = j; Position Parent Left hild Right hild Left Sibling Right Sibling Position value j 5 pos j rc
31 Heaps buildheap function aheap.buildheap(); aheap.siftdown(); aheap.siftdown(); aheap.siftdown(); aheap.siftdown(); aheap.siftdown(); aheap.siftdown(); Heaps removemax function template <class Elem, class omp> bool maxheap<elem, omp>:: removemax(elem& it) { if (n == ) return false; // Heap is empty swap(heap,, n); // Swap max with end if (n!= ) siftdown(); it = Heap[n]; // Return max value return true; aheap.removemax(avalue); avalue = 4 6
32 Heaps remove function Refer to Figure 5., pp template <class Elem, class omp> bool maxheap<elem, omp>::remove(int pos, Elem& it) { bool flag = false; if ((pos < ) (pos >= n)) return false; swap(heap, pos, n); while ((pos!= ) && (omp::gt(heap[pos],heap[parent(pos)]))) { swap(heap, pos, parent(pos)); pos = parent(pos); flag=true; if (!flag) siftdown(pos); it = Heap[n]; return true; 64 9 avalue = aheap.remove(, avalue); Heaps remove function 6 Refer to Figure 5., pp template <class Elem, class omp> bool maxheap<elem, omp>::remove(int pos, Elem& it) { bool flag = false; if ((pos < ) (pos >= n)) return false; swap(heap, pos, n); while ((pos!= ) && (omp::gt(heap[pos],heap[parent(pos)]))) { swap(heap, pos, parent(pos)); pos = parent(pos); flag=true; if (!flag) siftdown(pos); it = Heap[n]; return true; avalue = 9 aheap.remove(, avalue);
33 Heaps insert function template <class Elem, class omp> // Insert element bool maxheap<elem, omp>::insert(const Elem& val) { if (n >= size) return false; // Heap is full int curr = n++; Heap[curr] = val; // Start at end of heap // Now sift up until curr's parent > curr while ((curr!=) && (omp::gt(heap[curr], Heap[parent(curr)]))) { swap(heap, curr, parent(curr)); curr = parent(curr); 9 return true; 59 6 aheap.insert(9); Small Exercise!!!! ah.buildheap(); ah.removemax(temp); ah.remove(, temp); ah.insert(45); public void buildheap() { for (int i=n/-; i>=; i) siftdown(i); ah.siftdown(5); 55 ah.siftdown(); ah (maxheap) 66
34 Small Exercise!!!! ah.siftdown(5); ah.siftdown(); ah.siftdown(); ah.siftdown(4); ah.siftdown(); ah.siftdown(); Small Exercise!!!! ah.removemax(temp);
35 Small Exercise!!!! ah.remove(, temp); Small Exercise!!!! ah.insert(45);
36 Heaps When a heap with size n is created, there are two choices: Buildheap function Insert n values to a heap using insert function Which one is better? Heaps Time omplexity Insert n values to a heap Insert one value takes Θ(log n) in the worst case Move from the bottom to the top of the tree Buildheap function (n values in the array) epends on number of shiftdown calls n i= logn i= log i=θ( n log n n ( i ) i = Θ( n) ) x x 4x We should use buildheap to build the heap 4 i- n/ i 8 4 n=6
37 Heaps: Priority Queues A priority queue stores objects, and on request releases the object with greatest value Example: Scheduling jobs in a multi-tasking operating system Heaps: Priority Queues Possible Solutions: Linked List Insert appends to a linked list ( O() ) Remove max value determines the maximum by scanning the list ( O(n) ) Sorted Linked List (decreasing order) Insert places an element in its correct position ( O(n) ) Remove max value simply removes the head of the list ( O() ) Heap Both insert and remove max value are O( log n ) operations 4
38 Huffman oding Trees An entropy encoding algorithm used for lossless data compression Use a variable-length code table for encoding a source symbol erived based on the estimated probability of occurrence for each possible value 5 Huffman oding Trees Fixed-Length oding ASII codes: 8 bits per character E : : Variable-Length oding an take advantage of relative frequency of letters to save space K F U L E Use larger number of bits to store it Use smaller number of bits to store it 6
39 Huffman oding Trees Build the tree with minimum external path weight ombine the two smallest values each time K 4 M 4 L U 4 E Huffman oding Trees 6 9 K 65 4 M 86 E 9 4 L U 4 Letter E M K L U Freq ode Bit
40 Huffman oding Trees Huffman oding has the prefix property No code in the set is the prefix of another Non-prefix example: A: B: : What is? More than one solutions AA BA ecode: U M E Letter Freq ode 4 E M 4 K L 4 U Bit Huffman oding Trees Expected ost Expected ost per letter (how many bits have been used for a letter in average?) Letter Freq ode Bit (*+*+4*+5*4+6*9) 6 = 85/6 E M =.5 K 6 L 4 U 6 8
41 Huffman oding Trees Huffman Node AT template <class Elem> class HuffNode { // Node abstract base class public: virtual int weight() = ; 65 4 M 9 K virtual bool isleaf() = ; virtual HuffNode* left() const = ; virtual void setleft(huffnode*) = ; virtual HuffNode* right() const = ; virtual void setright(huffnode*) = ; ; 8 Huffman oding Trees FreqPair template <class Elem> class FreqPair { // An element/frequency pair private: Elem it; // An element of some sort int freq; // Frequency for the element public: FreqPair(const Elem& e, int f) // onstructor { it = e; freq = f; ~FreqPair() { // estructor int weight() { return freq; // Return the weight Elem& val() { return it; // Return the element ; 65 4 M 9 K 8
42 Huffman oding Trees Leaf Node template <class Elem> // leaf node subclass class LeafNode: public HuffNode<Elem> { private: Freqpair<Elem>* it; // Frequency pair 65 4 M 9 K public: LeafNode(const Elem& val, int freq) //constructor { it = new Freqpair<Elem>(val,freq); int weight() Freqpair<Elem>* val() { return it; bool isleaf() { return true; virtual HuffNode* left() const { return ; virtual void setleft(huffnode*) { virtual HuffNode* right() const { return ; virtual void setright(huffnode*) { ; { return it->weight(); //Return frequency 8 Huffman oding Trees Internal Node template <class Elem> //Internal node subclass 4 9 class IntlNode: public HuffNode<Elem> { M private: HuffNode<Elem>* lc; //left child K HuffNode<Elem>* rc; //right child int wgt; //Subtree weight public: IntlNode(HuffNode<Elem> * l; HuffNode<Elem> * r) { wgt = l->weight() + r->weight(); lc = l; rc = r; int weight() { return wgt; // Return frequency bool isleaf() { return false; HuffNode<Elem>* left() const { return lc; void setleft(huffnode<elem>* b) { lc = (HuffNode*)b; HuffNode<Elem>* right() const { return rc; void setright(huffnode<elem>* b) { rc = (HuffNode*)b; ; 65 9 K 84
43 Huffman oding Trees Huffman Tree template <class Elem> class HuffTree { private: HuffNode<Elem>* theroot; public: HuffTree(Elem& val, int freq) { theroot = new LeafNode<Elem>(val,freq); HuffTree(HuffTree<Elem>* l, HuffTree<Elem>* r) { theroot = new IntlNode<Elem>(l->root(), r->root()); ~HuffTree() { 65 4 M 9 K HuffNode<Elem>* root() { return theroot; int weight() { return theroot->weight(); ; 85 Huffman oding Trees Huffman ompare 4 M template <class Elem> class HHompare { public: static bool lt(hufftree<elem>* x, HuffTree<Elem>* y) { return x->weight() < y->weight(); static bool eq(hufftree<elem>* x, HuffTree<Elem>* y) { return x->weight() = = y->weight(); static bool gt(hufftree<elem>* x, HuffTree<Elem>* y) { return x->weight() > y->weight(); ; 65 9 K 86
44 Huffman oding Trees Build Huffman Tree template <class Elem> HuffTree<Elem>* Use Huffman ompare in SLL buildhuff(sllist<hufftree<elem>*,hhompare<elem>>* f) { HuffTree<Elem>* temp, *temp, *temp; for (f->setstart(); f->leftlength() + f->rightlength()>; f->setstart()) { //While at least two items left f->remove(temp); // Pull first two trees off the list f->remove(temp); temp = new HuffTree<Elem>(temp, temp); f->insert(temp); // Put the new tree back on list delete temp; // elete the remnants delete temp; return temp; temp temp f Sorted Linked List (SLL) Element of SLL is Huffman Tree 9 K K 4 M temp 8 Huffman oding Trees Build Huffman Tree: Example U 9 K K M 4 M K 4 L 4 M U U U K 4 L 4 L 4 L 4 M E E E E 4 L U K 4 L 4 M U K E E 4 M 88
45 Huffman oding Trees Build Huffman Tree: Example U L 65 9 K E 4 M U L K E 4 M 89
Heap: Complete binary tree with the heap property: Min-heap: All values less than child values. Max-heap: All values greater than child values.
Heaps Heap: Complete binary tree with the heap property: Min-heap: All values less than child values. Max-heap: All values greater than child values. The values are partially ordered. Heap representation:
More informationChapter 5. Binary Trees
Chapter 5 Binary Trees Definitions and Properties A binary tree is made up of a finite set of elements called nodes It consists of a root and two subtrees There is an edge from the root to its children
More informationData Structure Lecture#12: Binary Trees 3 (Chapter 5) U Kang Seoul National University
Data Structure Lecture#12: Binary Trees 3 (Chapter 5) U Kang Seoul National University U Kang (2016) 1 In This Lecture Motivation of Priority Queue data structure Main ideas and implementations of Heap
More informationbinary tree empty root subtrees Node Children Edge Parent Ancestor Descendant Path Depth Height Level Leaf Node Internal Node Subtree
Binary Trees A binary tree is made up of a finite set of nodes that is either empty or consists of a node called the root together with two binary trees called the left and right subtrees which are disjoint
More informationBinary Trees. Directed, Rooted Tree. Terminology. Trees. Binary Trees. Possible Implementation 4/18/2013
Directed, Rooted Tree Binary Trees Chapter 5 CPTR 318 Every non-empty directed, rooted tree has A unique element called root One or more elements called leaves Every element except root has a unique parent
More informationPriority Queues and Heaps (Ch 5.5) Huffman Coding Trees (Ch 5.6) Binary Search Trees (Ch 5.4) Lec 5: Binary Tree. Dr. Patrick Chan
ata Structure hapter Biary Trees r. Patrick ha School of om puter Sciece ad Egieerig South hia Uiversity of Techolog y Recursio recursio is a procedure which calls itself The recursive procedure call must
More informationData Structure Lecture#11: Binary Trees (Chapter 5) U Kang Seoul National University
Data Structure Lecture#11: Binary Trees (Chapter 5) U Kang Seoul National University U Kang (2016) 1 In This Lecture Implementation and space overhead of binary tree Main idea and operations for BST (Binary
More informationData Structure Chapter 6
ata Structure hapter Non-inary Trees r. Patrick han School of omputer Science and ngineering South hina University of Technology Outline Non-inary (eneral) Tree (h.) Parent Pointer mplementation (h.) ist
More informationBinary Trees, Binary Search Trees
Binary Trees, Binary Search Trees Trees Linear access time of linked lists is prohibitive Does there exist any simple data structure for which the running time of most operations (search, insert, delete)
More informationTrees, Binary Trees, and Binary Search Trees
COMP171 Trees, Binary Trees, and Binary Search Trees 2 Trees Linear access time of linked lists is prohibitive Does there exist any simple data structure for which the running time of most operations (search,
More informationChapter 20: Binary Trees
Chapter 20: Binary Trees 20.1 Definition and Application of Binary Trees Definition and Application of Binary Trees Binary tree: a nonlinear linked list in which each node may point to 0, 1, or two other
More informationBinary Trees and Binary Search Trees
Binary Trees and Binary Search Trees Learning Goals After this unit, you should be able to... Determine if a given tree is an instance of a particular type (e.g. binary, and later heap, etc.) Describe
More informationIndexing. Outline. Introduction (Ch 10) Linear Index (Ch 10.1) Tree Index (Ch 10.3) 2-3 Tree (Ch 10.4) B-Tree (Ch 10.5) Data Structure Chapter 10
http://125.216.243.100/csds/ Data Structure Chapter 10 Indexing Dr. Patrick Chan School of Computer Science and Engineering South China University of Technology Outline Introduction (Ch 10) Linear Index
More informationA set of nodes (or vertices) with a single starting point
Binary Search Trees Understand tree terminology Understand and implement tree traversals Define the binary search tree property Implement binary search trees Implement the TreeSort algorithm 2 A set of
More informationIndexing. Introduction. Outline. Search Approach. Linear Index (Ch 10.1) Tree Index (Ch 10.3) 2-3 Tree (Ch 10.4) B-Tree (Ch 10.5) Introduction (Ch 10)
http://125.216.243.100/csds/ Data Structure Chapter 10 Indexing Dr. Patrick Chan School of Computer Science and Engineering South China University of Technology Search Approach Sequential and List Method
More informationTree: non-recursive definition. Trees, Binary Search Trees, and Heaps. Tree: recursive definition. Tree: example.
Trees, Binary Search Trees, and Heaps CS 5301 Fall 2013 Jill Seaman Tree: non-recursive definition Tree: set of nodes and directed edges - root: one node is distinguished as the root - Every node (except
More informationHeaps. Heaps. A heap is a complete binary tree.
A heap is a complete binary tree. 1 A max-heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. A min-heap is defined
More informationTREES. Trees - Introduction
TREES Chapter 6 Trees - Introduction All previous data organizations we've studied are linear each element can have only one predecessor and successor Accessing all elements in a linear sequence is O(n)
More informationData Structures. Trees. By Dr. Mohammad Ali H. Eljinini. M.A. Eljinini, PhD
Data Structures Trees By Dr. Mohammad Ali H. Eljinini Trees Are collections of items arranged in a tree like data structure (none linear). Items are stored inside units called nodes. However: We can use
More informationLec 17 April 8. Topics: binary Trees expression trees. (Chapter 5 of text)
Lec 17 April 8 Topics: binary Trees expression trees Binary Search Trees (Chapter 5 of text) Trees Linear access time of linked lists is prohibitive Heap can t support search in O(log N) time. (takes O(N)
More information! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge
Trees (& Heaps) Week 12 Gaddis: 20 Weiss: 21.1-3 CS 5301 Spring 2015 Jill Seaman 1 Tree: non-recursive definition! Tree: set of nodes and directed edges - root: one node is distinguished as the root -
More informationBinary Trees. For example: Jargon: General Binary Trees. root node. level: internal node. edge. leaf node. Data Structures & File Management
Binary Trees 1 A binary tree is either empty, or it consists of a node called the root together with two binary trees called the left subtree and the right subtree of the root, which are disjoint from
More informationBinary Tree Node Relationships. Binary Trees. Quick Application: Expression Trees. Traversals
Binary Trees 1 Binary Tree Node Relationships 2 A binary tree is either empty, or it consists of a node called the root together with two binary trees called the left subtree and the right subtree of the
More informationBinary Tree. Binary tree terminology. Binary tree terminology Definition and Applications of Binary Trees
Binary Tree (Chapter 0. Starting Out with C++: From Control structures through Objects, Tony Gaddis) Le Thanh Huong School of Information and Communication Technology Hanoi University of Technology 11.1
More informationData Structures and Algorithms
Data Structures and Algorithms Spring 2017-2018 Outline 1 Priority Queues Outline Priority Queues 1 Priority Queues Jumping the Queue Priority Queues In normal queue, the mode of selection is first in,
More informationTrees. (Trees) Data Structures and Programming Spring / 28
Trees (Trees) Data Structures and Programming Spring 2018 1 / 28 Trees A tree is a collection of nodes, which can be empty (recursive definition) If not empty, a tree consists of a distinguished node r
More informationBinary Trees
Binary Trees 4-7-2005 Opening Discussion What did we talk about last class? Do you have any code to show? Do you have any questions about the assignment? What is a Tree? You are all familiar with what
More information! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge
Trees & Heaps Week 12 Gaddis: 20 Weiss: 21.1-3 CS 5301 Fall 2018 Jill Seaman!1 Tree: non-recursive definition! Tree: set of nodes and directed edges - root: one node is distinguished as the root - Every
More informationCS 234. Module 8. November 15, CS 234 Module 8 ADT Priority Queue 1 / 22
CS 234 Module 8 November 15, 2018 CS 234 Module 8 ADT Priority Queue 1 / 22 ADT Priority Queue Data: (key, element pairs) where keys are orderable but not necessarily distinct, and elements are any data.
More information國立清華大學電機工程學系. Outline
國立清華大學電機工程學系 2410 ata Structure hapter 5 Trees (Part I) Outline Introduction inary Trees inary Tree Traversal dditional inary Tree Operations Threaded inary Trees Heaps ch5.1-2 Genealogical harts no inbreeding
More informationTopic Binary Trees (Non-Linear Data Structures)
Topic Binary Trees (Non-Linear Data Structures) CIS210 1 Linear Data Structures Arrays Linked lists Skip lists Self-organizing lists CIS210 2 Non-Linear Data Structures Hierarchical representation? Trees
More informationCSCI Trees. Mark Redekopp David Kempe
CSCI 104 2-3 Trees Mark Redekopp David Kempe Trees & Maps/Sets C++ STL "maps" and "sets" use binary search trees internally to store their keys (and values) that can grow or contract as needed This allows
More informationBinary Trees. Height 1
Binary Trees Definitions A tree is a finite set of one or more nodes that shows parent-child relationship such that There is a special node called root Remaining nodes are portioned into subsets T1,T2,T3.
More informationCMSC 341 Lecture 15 Leftist Heaps
Based on slides from previous iterations of this course CMSC 341 Lecture 15 Leftist Heaps Prof. John Park Review of Heaps Min Binary Heap A min binary heap is a Complete binary tree Neither child is smaller
More informationCMSC 341 Lecture 15 Leftist Heaps
Based on slides from previous iterations of this course CMSC 341 Lecture 15 Leftist Heaps Prof. John Park Review of Heaps Min Binary Heap A min binary heap is a Complete binary tree Neither child is smaller
More informationMID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.
MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. In linked list the elements are necessarily to be contiguous In linked list the elements may locate at far positions
More informationBinary Trees. Examples:
Binary Trees A tree is a data structure that is made of nodes and pointers, much like a linked list. The difference between them lies in how they are organized: In a linked list each node is connected
More informationDiscussion 2C Notes (Week 8, February 25) TA: Brian Choi Section Webpage:
Discussion 2C Notes (Week 8, February 25) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs32 Trees Definitions Yet another data structure -- trees. Just like a linked
More informationINF2220: algorithms and data structures Series 1
Universitetet i Oslo Institutt for Informatikk A. Maus, R.K. Runde, I. Yu INF2220: algorithms and data structures Series 1 Topic Trees & estimation of running time (Exercises with hints for solution) Issued:
More informationBinary Tree. Preview. Binary Tree. Binary Tree. Binary Search Tree 10/2/2017. Binary Tree
0/2/ Preview Binary Tree Tree Binary Tree Property functions In-order walk Pre-order walk Post-order walk Search Tree Insert an element to the Tree Delete an element form the Tree A binary tree is a tree
More informationProgramming II (CS300)
1 Programming II (CS300) Chapter 11: Binary Search Trees MOUNA KACEM mouna@cs.wisc.edu Fall 2018 General Overview of Data Structures 2 Introduction to trees 3 Tree: Important non-linear data structure
More informationTrees. Introduction & Terminology. February 05, 2018 Cinda Heeren / Geoffrey Tien 1
Trees Introduction & Terminology Cinda Heeren / Geoffrey Tien 1 Review: linked lists Linked lists are constructed out of nodes, consisting of a data element a pointer to another node Lists are constructed
More informationTree Data Structures CSC 221
Tree Data Structures CSC 221 Specialized Trees Binary Tree: A restriction of trees such that the maximum degree of a node is 2. Order of nodes is now relevant May have zero nodes (emtpy tree) Formal Definition:
More informationPriority Queues. 1 Introduction. 2 Naïve Implementations. CSci 335 Software Design and Analysis III Chapter 6 Priority Queues. Prof.
Priority Queues 1 Introduction Many applications require a special type of queuing in which items are pushed onto the queue by order of arrival, but removed from the queue based on some other priority
More informationMULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR
STUDENT IDENTIFICATION NO MULTIMEDIA COLLEGE JALAN GURNEY KIRI 54100 KUALA LUMPUR FIFTH SEMESTER FINAL EXAMINATION, 2014/2015 SESSION PSD2023 ALGORITHM & DATA STRUCTURE DSEW-E-F-2/13 25 MAY 2015 9.00 AM
More informationIX. Binary Trees (Chapter 10)
IX. Binary Trees (Chapter 10) -1- A. Introduction: Searching a linked list. 1. Linear Search /* To linear search a list for a particular Item */ 1. Set Loc = 0; 2. Repeat the following: a. If Loc >= length
More informationData Structure Lecture#10: Binary Trees (Chapter 5) U Kang Seoul National University
Data Structure Lecture#10: Binary Trees (Chapter 5) U Kang Seoul National University U Kang (2016) 1 In This Lecture The concept of binary tree, its terms, and its operations Full binary tree theorem Idea
More informationCOMP : Trees. COMP20012 Trees 219
COMP20012 3: Trees COMP20012 Trees 219 Trees Seen lots of examples. Parse Trees Decision Trees Search Trees Family Trees Hierarchical Structures Management Directories COMP20012 Trees 220 Trees have natural
More informationTrees. A tree is a directed graph with the property
2: Trees Trees A tree is a directed graph with the property There is one node (the root) from which all other nodes can be reached by exactly one path. Seen lots of examples. Parse Trees Decision Trees
More informationCMSC 341 Lecture 14: Priority Queues, Heaps
CMSC 341 Lecture 14: Priority Queues, Heaps Prof. John Park Based on slides from previous iterations of this course Today s Topics Priority Queues Abstract Data Type Implementations of Priority Queues:
More informationMarch 20/2003 Jayakanth Srinivasan,
Definition : A simple graph G = (V, E) consists of V, a nonempty set of vertices, and E, a set of unordered pairs of distinct elements of V called edges. Definition : In a multigraph G = (V, E) two or
More informationPriority Queues. Chapter 9
Chapter 9 Priority Queues Sometimes, we need to line up things according to their priorities. Order of deletion from such a structure is determined by the priority of the elements. For example, when assigning
More informationCSI33 Data Structures
Outline Department of Mathematics and Computer Science Bronx Community College November 13, 2017 Outline Outline 1 C++ Supplement.1: Trees Outline C++ Supplement.1: Trees 1 C++ Supplement.1: Trees Uses
More informationFinal Exam Solutions PIC 10B, Spring 2016
Final Exam Solutions PIC 10B, Spring 2016 Problem 1. (10 pts) Consider the Fraction class, whose partial declaration was given by 1 class Fraction { 2 public : 3 Fraction ( int num, int den ); 4... 5 int
More informationCMSC 341 Leftist Heaps
CMSC 341 Leftist Heaps Based on slides from previous iterations of this course Today s Topics Review of Min Heaps Introduction of Left-ist Heaps Merge Operation Heap Operations Review of Heaps Min Binary
More informationCSE 214 Computer Science II Heaps and Priority Queues
CSE 214 Computer Science II Heaps and Priority Queues Spring 2018 Stony Brook University Instructor: Shebuti Rayana shebuti.rayana@stonybrook.edu http://www3.cs.stonybrook.edu/~cse214/sec02/ Introduction
More informationCSCI 104 Binary Trees / Priority Queues / Heaps. Mark Redekopp Michael Crowley
CSCI 04 Binary Trees / Priority Queues / Heaps Mark Redekopp Michael Crowley Trees Definition: A connected, acyclic (no cycles) graph with: A root node, r, that has 0 or more subtrees Exactly one path
More informationCHAPTER 5. Trees CHAPTER 5 1/70
CHAPTER 5 Trees All the programs in this file are selected from Ellis Horowitz, Sartaj Sahni, and Susan Anderson-Freed Fundamentals of Data Structures in C /2nd Edition, Silicon Press, 2008. CHAPTER 5
More informationAnalysis of Algorithms
Analysis of Algorithms Trees-I Prof. Muhammad Saeed Tree Representation.. Analysis Of Algorithms 2 .. Tree Representation Analysis Of Algorithms 3 Nomenclature Nodes (13) Size (13) Degree of a node Depth
More informationTrees! Ellen Walker! CPSC 201 Data Structures! Hiram College!
Trees! Ellen Walker! CPSC 201 Data Structures! Hiram College! ADTʼs Weʼve Studied! Position-oriented ADT! List! Stack! Queue! Value-oriented ADT! Sorted list! All of these are linear! One previous item;
More informationFINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 ( Marks: 1 ) - Please choose one The data of the problem is of 2GB and the hard
FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 The data of the problem is of 2GB and the hard disk is of 1GB capacity, to solve this problem we should Use better data structures
More informationTree. A path is a connected sequence of edges. A tree topology is acyclic there is no loop.
Tree A tree consists of a set of nodes and a set of edges connecting pairs of nodes. A tree has the property that there is exactly one path (no more, no less) between any pair of nodes. A path is a connected
More informationTree Structures. A hierarchical data structure whose point of entry is the root node
Binary Trees 1 Tree Structures A tree is A hierarchical data structure whose point of entry is the root node This structure can be partitioned into disjoint subsets These subsets are themselves trees and
More informationTrees can be used to store entire records from a database, serving as an in-memory representation of the collection of records in a file.
Large Trees 1 Trees can be used to store entire records from a database, serving as an in-memory representation of the collection of records in a file. Trees can also be used to store indices of the collection
More informationData Structures Question Bank Multiple Choice
Section 1. Fundamentals: Complexity, Algorthm Analysis 1. An algorithm solves A single problem or function Multiple problems or functions Has a single programming language implementation 2. A solution
More informationData Structures and Algorithms
Data Structures and Algorithms CS245-2017S-06 Binary Search Trees David Galles Department of Computer Science University of San Francisco 06-0: Ordered List ADT Operations: Insert an element in the list
More information8. Binary Search Tree
8 Binary Search Tree Searching Basic Search Sequential Search : Unordered Lists Binary Search : Ordered Lists Tree Search Binary Search Tree Balanced Search Trees (Skipped) Sequential Search int Seq-Search
More informationStacks, Queues and Hierarchical Collections
Programming III Stacks, Queues and Hierarchical Collections 2501ICT Nathan Contents Linked Data Structures Revisited Stacks Queues Trees Binary Trees Generic Trees Implementations 2 Copyright 2002- by
More informationBinary Search Trees Part Two
Binary Search Trees Part Two Recap from Last Time Binary Search Trees A binary search tree (or BST) is a data structure often used to implement maps and sets. The tree consists of a number of nodes, each
More informationModule 9: Binary trees
Module 9: Binary trees Readings: HtDP, Section 14 We will cover the ideas in the text using different examples and different terminology. The readings are still important as an additional source of examples.
More informationUses for Trees About Trees Binary Trees. Trees. Seth Long. January 31, 2010
Uses for About Binary January 31, 2010 Uses for About Binary Uses for Uses for About Basic Idea Implementing Binary Example: Expression Binary Search Uses for Uses for About Binary Uses for Storage Binary
More informationCSCI-401 Examlet #5. Name: Class: Date: True/False Indicate whether the sentence or statement is true or false.
Name: Class: Date: CSCI-401 Examlet #5 True/False Indicate whether the sentence or statement is true or false. 1. The root node of the standard binary tree can be drawn anywhere in the tree diagram. 2.
More informationA6-R3: DATA STRUCTURE THROUGH C LANGUAGE
A6-R3: DATA STRUCTURE THROUGH C LANGUAGE NOTE: 1. There are TWO PARTS in this Module/Paper. PART ONE contains FOUR questions and PART TWO contains FIVE questions. 2. PART ONE is to be answered in the TEAR-OFF
More informationPriority Queues (Heaps)
Priority Queues (Heaps) 1 Priority Queues Many applications require that we process records with keys in order, but not necessarily in full sorted order. Often we collect a set of items and process the
More informationUpcoming ACM Events Linux Crash Course Date: Time: Location: Weekly Crack the Coding Interview Date:
Upcoming ACM Events Linux Crash Course Date: Oct. 2nd and 3rd Time: 1:15 pm - 3:15 pm Location: UW1-210 (10/02) and UW1-221 (10/03) Weekly Crack the Coding Interview Date: Weekly Fridays from Oct. 5th
More informationPriority Queues and Heaps. Heaps of fun, for everyone!
Priority Queues and Heaps Heaps of fun, for everyone! Learning Goals After this unit, you should be able to... Provide examples of appropriate applications for priority queues and heaps Manipulate data
More informationH.O.#12 Fall 2015 Gary Chan. Binary Tree (N:12)
H.O.#12 Fall 2015 Gary Chan Binary Tree (N:12) Outline Binary tree terminology Tree traversals: preorder, inorder and postorder Dictionary and binary search tree Binary search tree operations Search min
More informationCMSC 341 Priority Queues & Heaps. Based on slides from previous iterations of this course
CMSC 341 Priority Queues & Heaps Based on slides from previous iterations of this course Today s Topics Priority Queues Abstract Data Type Implementations of Priority Queues: Lists BSTs Heaps Heaps Properties
More informationMIDTERM EXAMINATION Spring 2010 CS301- Data Structures
MIDTERM EXAMINATION Spring 2010 CS301- Data Structures Question No: 1 Which one of the following statement is NOT correct. In linked list the elements are necessarily to be contiguous In linked list the
More informationSection 5.5. Left subtree The left subtree of a vertex V on a binary tree is the graph formed by the left child L of V, the descendents
Section 5.5 Binary Tree A binary tree is a rooted tree in which each vertex has at most two children and each child is designated as being a left child or a right child. Thus, in a binary tree, each vertex
More informationAlgorithms and Data Structures
Lesson 3: trees and visits Luciano Bononi http://www.cs.unibo.it/~bononi/ (slide credits: these slides are a revised version of slides created by Dr. Gabriele D Angelo) International
More informationTrees. Q: Why study trees? A: Many advance ADTs are implemented using tree-based data structures.
Trees Q: Why study trees? : Many advance DTs are implemented using tree-based data structures. Recursive Definition of (Rooted) Tree: Let T be a set with n 0 elements. (i) If n = 0, T is an empty tree,
More informationModule 4: Index Structures Lecture 13: Index structure. The Lecture Contains: Index structure. Binary search tree (BST) B-tree. B+-tree.
The Lecture Contains: Index structure Binary search tree (BST) B-tree B+-tree Order file:///c /Documents%20and%20Settings/iitkrana1/My%20Documents/Google%20Talk%20Received%20Files/ist_data/lecture13/13_1.htm[6/14/2012
More informationCS302 - Data Structures using C++
CS302 - Data Structures using C++ Topic: Trees Kostas Alexis Trees List, stacks, and queues are linear in their organization of data. Items are one after another In this section, we organize data in a
More informationPriority Queues (Heaps)
Priority Queues (Heaps) October 11, 2016 CMPE 250 Priority Queues October 11, 2016 1 / 29 Priority Queues Many applications require that we process records with keys in order, but not necessarily in full
More informationCS102 Binary Search Trees
CS102 Binary Search Trees Prof Tejada 1 To speed up insertion, removal and search, modify the idea of a Binary Tree to create a Binary Search Tree (BST) Binary Search Trees Binary Search Trees have one
More informationAn Introduction to Trees
An Introduction to Trees Alice E. Fischer Spring 2017 Alice E. Fischer An Introduction to Trees... 1/34 Spring 2017 1 / 34 Outline 1 Trees the Abstraction Definitions 2 Expression Trees 3 Binary Search
More informationCSE100 Practice Final Exam Section C Fall 2015: Dec 10 th, Problem Topic Points Possible Points Earned Grader
CSE100 Practice Final Exam Section C Fall 2015: Dec 10 th, 2015 Problem Topic Points Possible Points Earned Grader 1 The Basics 40 2 Application and Comparison 20 3 Run Time Analysis 20 4 C++ and Programming
More information3. Priority Queues. ADT Stack : LIFO. ADT Queue : FIFO. ADT Priority Queue : pick the element with the lowest (or highest) priority.
3. Priority Queues 3. Priority Queues ADT Stack : LIFO. ADT Queue : FIFO. ADT Priority Queue : pick the element with the lowest (or highest) priority. Malek Mouhoub, CS340 Winter 2007 1 3. Priority Queues
More informationBBM 201 Data structures
BBM 201 Data structures Lecture 11: Trees 2018-2019 Fall Content Terminology The Binary Tree The Binary Search Tree Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, 2013
More informationLecture Notes 16 - Trees CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson
Lecture Notes 16 - Trees CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson Reading: Carrano, Chapter 15 Introduction to trees The data structures we have seen so far to implement
More informationGarbage Collection: recycling unused memory
Outline backtracking garbage collection trees binary search trees tree traversal binary search tree algorithms: add, remove, traverse binary node class 1 Backtracking finding a path through a maze is an
More informationChapter 12: Searching: Binary Trees and Hash Tables. Exercises 12.1
Chapter 12: Searching: Binary Trees and Hash Tables Exercises 12.1 1. 4, 6 2. 4, 1, 2, 3 3. 4, 6, 5 4. 4, 1, 0 5. 4, 6, 7, 8 6. template linearsearch(elementtype x[], ElementType
More informationStacks, Queues and Hierarchical Collections. 2501ICT Logan
Stacks, Queues and Hierarchical Collections 2501ICT Logan Contents Linked Data Structures Revisited Stacks Queues Trees Binary Trees Generic Trees Implementations 2 Queues and Stacks Queues and Stacks
More informationLecture 2. Binary Trees & Implementations. Yusuf Pisan
CSS 343 Data Structures, Algorithms, and Discrete Math II Lecture 2 Binary Trees & Implementations Yusuf Pisan Overview 1. Huffman Coding and Arithmetic Expressions 2. 342 Topics a. Pointers & References
More informationTREES Lecture 10 CS2110 Spring2014
TREES Lecture 10 CS2110 Spring2014 Readings and Homework 2 Textbook, Chapter 23, 24 Homework: A thought problem (draw pictures!) Suppose you use trees to represent student schedules. For each student there
More informationIntroduction to Computers and Programming. Concept Question
Introduction to Computers and Programming Prof. I. K. Lundqvist Lecture 7 April 2 2004 Concept Question G1(V1,E1) A graph G(V, where E) is V1 a finite = {}, nonempty E1 = {} set of G2(V2,E2) vertices and
More informationComputational Optimization ISE 407. Lecture 16. Dr. Ted Ralphs
Computational Optimization ISE 407 Lecture 16 Dr. Ted Ralphs ISE 407 Lecture 16 1 References for Today s Lecture Required reading Sections 6.5-6.7 References CLRS Chapter 22 R. Sedgewick, Algorithms in
More informationTrees: examples (Family trees)
Ch 4: Trees it s a jungle out there... I think that I will never see a linked list useful as a tree; Linked lists are used by everybody, but it takes real smarts to do a tree Trees: examples (Family trees)
More informationCSE100. Advanced Data Structures. Lecture 13. (Based on Paul Kube course materials)
CSE100 Advanced Data Structures Lecture 13 (Based on Paul Kube course materials) CSE 100 Priority Queues in Huffman s algorithm Heaps and Priority Queues Time and space costs of coding with Huffman codes
More information