Binary Trees CS 400/600 – Data Structures. Binary Trees2 A binary tree is made up of a finite set of nodes that is either empty or consists of a node.

Slides:



Advertisements
Similar presentations
COL 106 Shweta Agrawal and Amit Kumar
Advertisements

Binary Trees CSC 220. Your Observations (so far data structures) Array –Unordered Add, delete, search –Ordered Linked List –??
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.
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.
1 Dictionary Often want to insert records, delete records, search for records. Required concepts: Search key: Describe what we are looking for Key comparison.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
CMPT 225 Priority Queues and Heaps. Priority Queues Items in a priority queue have a priority The priority is usually numerical value Could be lowest.
Fall 2007CS 2251 Trees Chapter 8. Fall 2007CS 2252 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information.
E.G.M. PetrakisTrees1  Definition (recursive): finite set of elements (nodes) which is either empty or it is partitioned into m + 1 disjoint subsets T.
Trees, Binary Trees, and Binary Search Trees COMP171.
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
Version TCSS 342, Winter 2006 Lecture Notes Priority Queues Heaps.
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,
E.G.M. PetrakisTrees1 Definition (recursive): finite set of elements (nodes) which is either empty or it is partitioned into m + 1 disjoint subsets T 0,T.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Fundamentals of Python: From First Programs Through Data Structures
Binary Search Trees Chapter 6.
1 BST Trees A binary search tree is a binary tree in which every node satisfies the following: the key of every node in the left subtree is.
Heapsort Based off slides by: David Matuszek
Data Structures Arrays both single and multiple dimensions Stacks Queues Trees Linked Lists.
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.
Recursion Bryce Boe 2013/11/18 CS24, Fall Outline Wednesday Recap Lab 7 Iterative Solution Recursion Binary Tree Traversals Lab 7 Recursive Solution.
UNCA CSCI September, 2001 These notes were prepared by the text’s author Clifford A. Shaffer Department of Computer Science Virginia Tech Copyright.
ADT Table and Heap Ellen Walker CPSC 201 Data Structures Hiram College.
CS 1031 Tree Traversal Techniques; Heaps Tree Traversal Concept Tree Traversal Techniques: Preorder, Inorder, Postorder Full Trees Almost Complete Trees.
Searching: Binary Trees and Hash Tables CHAPTER 12 6/4/15 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,
Lecture 10 Trees –Definiton of trees –Uses of trees –Operations on a tree.
Chapter 5 Binary Trees. Definitions and Properties A binary tree is made up of a finite set of elements called nodes A binary tree is made up of a finite.
Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
1 Trees A tree is a data structure used to represent different kinds of data and help solve a number of algorithmic problems Game trees (i.e., chess ),
For Monday Read Weiss, chapter 7, sections 1-3. Homework –Weiss, chapter 4, exercise 6. Make sure you include parentheses where appropriate.
Priority Queues and Binary Heaps Chapter Trees Some animals are more equal than others A queue is a FIFO data structure the first element.
Binary Trees, Binary Search Trees RIZWAN REHMAN CENTRE FOR COMPUTER STUDIES DIBRUGARH UNIVERSITY.
Chapter 21 Priority Queue: Binary Heap Saurav Karmakar.
CMSC 341 Binary Heaps Priority Queues. 2 Priority: some property of an object that allows it to be prioritized WRT other objects (of the same type) Priority.
Trees, Binary Trees, and Binary Search Trees COMP171.
Starting at Binary Trees
Priority Queue. Priority Queues Queue (FIFO). Priority queue. Deletion from a priority queue is determined by the element priority. Two kinds of priority.
1 Joe Meehean.  We wanted a data structure that gave us... the smallest item then the next smallest then the next and so on…  This ADT is called a priority.
Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.
Binary Search Trees (BSTs) 18 February Binary Search Tree (BST) An important special kind of binary tree is the BST Each node stores some information.
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
CMSC 341 Introduction to Trees. 2/21/20062 Tree ADT Tree definition –A tree is a set of nodes which may be empty –If not empty, then there is a distinguished.
UNCA CSCI September, 2001 These notes were prepared by the text’s author Clifford A. Shaffer Department of Computer Science Virginia Tech Copyright.
ADT Binary Search Tree Ellen Walker CPSC 201 Data Structures Hiram College.
Rooted Tree a b d ef i j g h c k root parent node (self) child descendent leaf (no children) e, i, k, g, h are leaves internal node (not a leaf) sibling.
Tree Data Structures. Heaps for searching Search in a heap? Search in a heap? Would have to look at root Would have to look at root If search item smaller.
1 Heaps A heap is a binary tree. A heap is best implemented in sequential representation (using an array). Two important uses of heaps are: –(i) efficient.
CMSC 341 Binary Heaps Priority Queues. 2 Priority: some property of an object that allows it to be prioritized WRT other objects (of the same type) Priority.
HEAPS. Review: what are the requirements of the abstract data type: priority queue? Quick removal of item with highest priority (highest or lowest key.
1 Joe Meehean. A A B B D D I I C C E E X X A A B B D D I I C C E E X X  Terminology each circle is a node pointers are edges topmost node is the root.
CMSC 202, Version 5/02 1 Trees. CMSC 202, Version 5/02 2 Tree Basics 1.A tree is a set of nodes. 2.A tree may be empty (i.e., contain no nodes). 3.If.
BINARY TREES Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary.
Search: Binary Search Trees Dr. Yingwu Zhu. Review: Linear Search Collection of data items to be searched is organized in a list x 1, x 2, … x n – Assume.
Course: Programming II - Abstract Data Types HeapsSlide Number 1 The ADT Heap So far we have seen the following sorting types : 1) Linked List sort by.
1 Trees. 2 Trees Trees. Binary Trees Tree Traversal.
Binary Tree ADT: Properties
BST Trees
Binary Trees, Binary Search Trees
Chapter 22 : Binary Trees, AVL Trees, and Priority Queues
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
Heaps and the Heapsort Heaps and priority queues
Binary Trees, Binary Search Trees
CSCI 333 Data Structures Chapter 5 18, 20, 23, and 25 September 2002.
Binary Trees, Binary Search Trees
Tree (new ADT) Terminology: A tree is a collection of elements (nodes)
Presentation transcript:

Binary Trees CS 400/600 – Data Structures

Binary Trees2 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 from each other and from the root.

Binary Trees3 Binary Tree Example Notation: Node, children, edge, parent, ancestor, descendant, path, depth, height, level, leaf node, internal node, subtree.

Binary Trees4 Traversals Any process for visiting the nodes in some order is called a traversal. Any traversal that lists every node in the tree exactly once is called an enumeration of the tree’s nodes.

Binary Trees5 Preorder  Visit current node, then visit each child, left-to-right: ABDCEGFHI  Naturally recursive: // preorder traversal void preorder(BinNode* current) { if (current == NULL) return; visit(current); preorder(current->left()); preorder(current->right()); }

Binary Trees6 Postorder  Visit each child, left- to-right, before the current node: DBGEHIFCA

Binary Trees7 Inorder  Only makes sense for binary trees.  Visit nodes in order: left child, current, right child. BDAGECHFI

Binary Trees8 Full and Complete Binary Trees Full binary tree: Each node is either a leaf or internal node with exactly two non-empty children. Complete 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 to the left side. Full, not complete Complete, not full

Binary Trees9 Full Binary Tree Theorem (1) Theorem: The number of leaves in a non-empty full binary tree is one more than the number of internal nodes. Proof (by Mathematical Induction): Base case: A full binary tree with 1 internal node must have two leaf nodes. Induction Hypothesis: Assume any full binary tree T containing n-1 internal nodes has n leaves.

Binary Trees10 Full Binary Tree Theorem (2) Induction Step: Given tree T with n internal nodes, pick internal node I with two leaf children. Remove I’s children, call resulting tree T’. By induction hypothesis, T’ is a full binary tree with n leaves. Restore I’s two children. The number of internal nodes has now gone up by 1 to reach n. The number of leaves has also gone up by 1.

Binary Trees11 Full Binary Tree Corollary Theorem: The number of null pointers in a non- empty tree is one more than the number of nodes in the tree. Proof: Replace all null pointers with a pointer to an empty leaf node. This is a full binary tree.

Binary Trees12 A Binary Tree Node ADT Class BinNode  Elem& val() – return the value of a node  void setVal(const Elem&) – set the value  BinNode* left() – return the left child  BinNode* right() – return the right child  void setLeft(BinNode*) – set the left child  void setRight(BinNode*) – set the right child  bool isLeaf() – return true if leaf node, else false

Binary Trees13 Representing Nodes  Simplest node representation: val leftright  All of the leaf nodes have two null pointers  How much wasted space? By our previous corollary, more empty pointers than nodes in the entire tree! Sometimes leaf nodes hold more (all) data.

Binary Trees14 Representing Nodes (2)  We can use inheritance to allow two kinds of nodes: internal and leaf nodes  Base class: VarBinNode isLeaf – pure virtual function  Derived classes: IntlNode and LeafNode  Typecast pointers once we know what kind of node we are working with…

Binary Trees15 Inheritance (1) class VarBinNode { // Abstract base class public: virtual bool isLeaf() = 0; }; class LeafNode : public VarBinNode { // Leaf private: Operand var; // Operand value public: LeafNode(const Operand& val) { var = val; } // Constructor bool isLeaf() { return true; } Operand value() { return var; } };

Binary Trees16 Inheritance (2) // Internal node class IntlNode : public VarBinNode { 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 Trees17 Inheritance (3) // Preorder traversal void traverse(VarBinNode *subroot) { if (subroot == NULL) return; // Empty if (subroot->isLeaf()) // Do leaf node cout << "Leaf: " value() << endl; else { // Do internal node cout << "Internal: " value() << endl; traverse(((IntlNode *)subroot)-> leftchild()); traverse(((IntlNode *)subroot)-> rightchild()); }

Binary Trees18 Space requirements for binary trees  Every node stores data (d) and two pointers (p) If p = d, about 2/3 overhead ½ of this overhead is null pointers

Binary Trees19 Space requirements for binary trees  No pointers in leaf nodes (~half of all nodes) If p = d, about one half of total space is overhead No null pointers

Binary Trees20 Complete Binary Trees  For a complete tree, we can save a lot of space by storing the tree in an array (no pointers!)

Binary Trees21 Array Representation Position Parent Left Child Right Child Left Sibling Right Sibling How can we find parents, children, siblings?

Binary Trees22 Array Relationships Position Parent Left Child Right Child Left Sibling Right Sibling

Binary Trees23 Binary Search Trees  BST Property: All elements stored in the left subtree of a node with value K have values = K.

Binary Trees24 Searching the tree Bool find(const Key& K, Elem& e) const { return findhelp(root, K, e); } template <class Key, class Elem, class KEComp, class EEComp> bool BST :: findhelp(BinNode * subroot, const Key& K, Elem& e) const { if (subroot == NULL) return false; else if (KEComp::lt(K, subroot->val())) return findhelp(subroot->left(), K, e); else if (KEComp::gt(K, subroot->val())) return findhelp(subroot->right(), K, e); else { e = subroot->val(); return true; } }

Binary Trees25 Inserting into the tree  Find an appropriate leaf node, or internal node with no left/right child  Insert the new value  Can cause the tree to become unbalanced

Binary Trees26 An unbalanced tree  Suppose we insert 3, 5, 7, 9, 11, 13,

Binary Trees27 Cost of search  Worst case cost = depth of tree Worst case: tree linear, cost = n Best case: perfect balance, cost = lg(n)

Binary Trees28 BST insert template <class Key, class Elem, class KEComp, class EEComp> BinNode * BST :: inserthelp(BinNode * subroot, const Elem& val) { if (subroot == NULL) // Empty: create node return new BinNodePtr (val,NULL,NULL); if (EEComp::lt(val, subroot->val())) subroot->setLeft(inserthelp(subroot->left(), val)); else subroot->setRight( inserthelp(subroot->right(), val)); // Return subtree with node inserted return subroot; }

Binary Trees29 Deleting  When deleting from a BST we must take care that… The resulting tree is still a binary tree The BST property still holds  To start with, consider the case of deleting the minimum element of a subtree

Binary Trees30 Removing the minimal node 1.Move left until you can’t any more Call the minimal node S 2.Have the parent of S point to the right child of S There was no left child, or we would have taken that link Still less than S’s parent, so BST property maintained NULL links are ok

Binary Trees31 Removing the min …deletemin(BinNode * subroot, BinNode *& min) { if (subroot->left() == NULL) { min = subroot; return subroot->right(); } else { // Continue left subroot->setLeft( deletemin(subroot->left(), min)); return subroot; }

Binary Trees32 DeleteMin deletemin(10) setleft(deletemin(8)) setleft(deletemin(5)) min = 5 return 6 return 8 return

Binary Trees33 Deleting an arbitrary node  If we delete an arbitrary node, R, from a BST, there are three possibilities: R has no children – set it’s parent’s pointer to null R has one child – set the parent’s pointer to point to the child, similar to deletemin R has two children – Now what?  We have to find a node from R’s subtree to replace R, in order to keep a binary tree.  We must be careful to maintain the BST property

Binary Trees34 Which node?  Which node can we use to replace R? Which node in the tree will be most similar to R? Depends on which subtree:  Left subtree: rightmost –Everything in the right subtree is greater, everything in the left subtree is smaller  Right subtree: leftmost –Everything in the left subtree is smaller, everything in the right subtree is greater

Binary Trees35 BST delete

Binary Trees36 Duplicate values  If there are no duplicates, either will work  Duplicates Recall that the left subtree has values < K, while the right has values  K. Duplicates of K must be in the right subtree, so we must choose from the right subtree if duplicates are allowed.

Binary Trees37 Heaps and priority queues  Sometimes we don’t need a completely sorted structure. Rather, we just want to get the highest priority item each time.  A heap is complete binary tree with one of the following two properties… Max-heap: every node stores a value greater than or equal to those of its children (no order imposed on children) Min-heap: every node stores a value less than or equal to those of its children

Binary Trees38 Max-heap not-so-abstract data type template 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(); };

Binary Trees39 Array representation  Since a heap is always complete, we can use the array representation for space savings

Binary Trees40 Heap insert  Add an element at the end of the heap  While (smaller than parent) {swap};

Binary Trees41 Batch insert  If we have the entire (unsorted) array at once, we can speed things up with a buildheap() function  If the right and left subtrees are already heaps, we can sift nodes down the correct level by exchanging the new root with the larger child value New structure will be a heap, except that R may not be the smallest value in its subtree Recursively sift R down to the correct level R h1h1 h2h2

Binary Trees42 Siftdown

Binary Trees43 Siftdown (2) For fast heap construction:  Work from high end of array to low end.  Call siftdown for each item.  Don’t need to call siftdown on leaf nodes. template void maxheap ::siftdown(int pos) { while (!isLeaf(pos)) { int j = leftchild(pos); int rc = rightchild(pos); if ((rc<n) && Comp::lt(Heap[j],Heap[rc])) j = rc; if (!Comp::lt(Heap[pos], Heap[j])) return; swap(Heap, pos, j); pos = j; }}

Binary Trees44 Cost of buildheap()  Work from high index to low so that subtrees will already be heaps  Leaf nodes can’t be sifted down further  Each siftdown can cost, at most, the number of steps for a node to reach the bottom of the tree Half the nodes, 0 steps (leaf nodes) One quarter: 1 step max One eighth: 2 steps max, etc.

Binary Trees45 The whole point  The most important operation: remove and return the max-priority element Can’t remove the root and maintain a complete binary tree shape The only element we can remove is the last element Swap last with root and siftdown()  (log n) in average and worst cases  Changing priorities: not efficient to find arbitrary elements, only the top. Use an additional data structure (BST) with pointers

Binary Trees46 Coding schemes  ASCII – a fixed length coding scheme:

Binary Trees47 Variable length scheme  In general, letters such as s, i, and e are used more often than, say z.  If the code for s is 01, and the code for z is , we might be able to save some space No other code can start with 01, or we will think it is an s

Binary Trees48 The Huffman Tree  A full binary tree with letters at the leaf nodes and labeled edges  Assign weights to the letters that represent how often they are used s – high weight, z – low weight  How do we decide how often? What type of communications?

Binary Trees49 Building a Huffman tree  To start, each character is its own (full) binary tree  Merge trees with lowest weights  New weight is sum of previous weights  Continue…

Binary Trees50 Building a Huffman tree (2)

Binary Trees51 Assigning codes LetterFreqCodeBits C32 D42 E120 F24 K7 L42 U37 Z2

Binary Trees52 Properties of Huffman codes  No letters at internal nodes, so no character has a code that is a prefix of another character’s code.  What if we write a message with a lot of z’s?  Average character cost: where