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.

Slides:



Advertisements
Similar presentations
COL 106 Shweta Agrawal and Amit Kumar
Advertisements

Heaps1 Part-D2 Heaps Heaps2 Recall Priority Queue ADT (§ 7.1.3) A priority queue stores a collection of entries Each entry is a pair (key, value)
Binary Trees CSC 220. Your Observations (so far data structures) Array –Unordered Add, delete, search –Ordered Linked List –??
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Binary Trees Chapter 6. Linked Lists Suck By now you realize that the title to this slide is true… By now you realize that the title to this slide is.
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.
Trees Chapter 8.
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 Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
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.
Lists A list is a finite, ordered sequence of data items. Two Implementations –Arrays –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,
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.
© 2006 Pearson Addison-Wesley. All rights reserved11 A-1 Chapter 11 Trees.
Priority Queues. Container of elements where each element has an associated key A key is an attribute that can identify rank or weight of an element Examples.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Trees Chapter 23 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Fundamentals of Python: From First Programs Through Data Structures
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.
Binary Trees Chapter 6.
Data Structures Arrays both single and multiple dimensions Stacks Queues Trees Linked Lists.
Trees. Tree Terminology Chapter 8: Trees 2 A tree consists of a collection of elements or nodes, with each node linked to its successors The node at the.
UNCA CSCI September, 2001 These notes were prepared by the text’s author Clifford A. Shaffer Department of Computer Science Virginia Tech Copyright.
Ceng-112 Data Structures I 1 Chapter 7 Introduction to Trees.
CS Data Structures Chapter 5 Trees. Chapter 5 Trees: Outline  Introduction  Representation Of Trees  Binary Trees  Binary Tree Traversals 
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.
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.
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.
CMSC 341 Introduction to Trees. 8/3/2007 UMBC CMSC 341 TreeIntro 2 Tree ADT Tree definition  A tree is a set of nodes which may be empty  If not empty,
Chapter 6 Binary Trees. 6.1 Trees, Binary Trees, and Binary Search Trees Linked lists usually are more flexible than arrays, but it is difficult to use.
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.
data ordered along paths from root to leaf
Chapter 21 Priority Queue: Binary Heap Saurav Karmakar.
Starting at Binary Trees
 Trees Data Structures Trees Data Structures  Trees Trees  Binary Search Trees Binary Search Trees  Binary Tree Implementation Binary Tree Implementation.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for use at Midwestern State University Chapter.
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.
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.
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.
HEAPS. Review: what are the requirements of the abstract data type: priority queue? Quick removal of item with highest priority (highest or lowest key.
Trees Ellen Walker CPSC 201 Data Structures Hiram College.
1 Trees General Trees  Nonrecursive definition: a tree consists of a set of nodes and a set of directed edges that connect pairs of nodes.
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.
1 Trees General Trees  Nonrecursive definition: a tree consists of a set of nodes and a set of directed edges that connect pairs of nodes.
Trees By JJ Shepherd. Introduction Last time we discussed searching and sorting in a more efficient way Divide and Conquer – Binary Search – Merge Sort.
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.
Chapter 11. Chapter Summary  Introduction to trees (11.1)  Application of trees (11.2)  Tree traversal (11.3)  Spanning trees (11.4)
1 CMSC 341 Introduction to Trees Textbook sections:
1 Trees. 2 Trees Trees. Binary Trees Tree Traversal.
Lecture on Data Structures(Trees). Prepared by, Jesmin Akhter, Lecturer, IIT,JU 2 Properties of Heaps ◈ Heaps are binary trees that are ordered.
Coursenotes CS3114: Data Structures and Algorithms Clifford A. Shaffer Yang Cao Department of Computer Science Virginia Tech Copyright ©
Trees Chapter 15.
Week 6 - Wednesday CS221.
Bohyung Han CSE, POSTECH
Binary Trees, Binary Search Trees
Ch. 11 Trees 사실을 많이 아는 것 보다는 이론적 틀이 중요하고, 기억력보다는 생각하는 법이 더 중요하다.
7/23/2009 Many thanks to David Sun for some of the included slides!
Find in a linked list? first last 7  4  3  8 NULL
CSCI 333 Data Structures Chapter 5 18, 20, 23, and 25 September 2002.
NATURE VIEW OF A TREE leaves branches root. NATURE VIEW OF A TREE leaves branches root.
Tree (new ADT) Terminology: A tree is a collection of elements (nodes)
Presentation transcript:

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 from each other and from the root Notation: Node, Children, Edge, Parent, Ancestor, Descendant, Path, Depth, Height, Level, Leaf Node, Internal Node, Subtree. A G FE C D B IH

Full and Complete Binary Trees A Full binary tree has each node being either a leaf or internal node with exactly two non-empty children. A 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 Binary Tree Theorem 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. Induction Step: Pick an arbitrary leaf node j of T. Make j an internal node by giving it 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. Corollary: The number of NULL pointers in a non-empty binary tee is one more than the number of nodes in the tree.

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. 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. void preorder(BinNode * root) { if (root==NULL) return; visit(root); preorder(root->leftchild()); preorder(root->rightchild()); }

Expression Trees Example of (a-b)/((x*y+3)-(6*z)) / - a b - + 6z * yx 3*

Binary Search Trees Left means less – right means greater. Find –If item dat then cur=cur->left –Else if item>cur->dat then cur=cur->right –Else found –Repeat while not found and cur not NULL No need for recursion.

Find min and max The min will be all the way to the left –While cur->left != NULL, cur=cur->left The max will be all the way to the right –While cur->right !=NULL, cur=cur->right Insert –Like a find, but stop when you would go to a null and insert there.

Remove If node to be deleted is a leaf (no children), can remove it and adjust the parent node (must keep track of previous) If the node to be deleted has one child, remove it and have the parent point to that child. If the node to be deleted has 2 children –Replace the data value with the smallest value in the right subtree –Delete the smallest value in the right subtree (it will have no left child, so a trivial delete.

Array Implementation For a complete binary tree Parent(x)= Leftchild(x)= Rightchild(x)= Leftsibling(x)= Rightsibling(x)= (x-1)/2 2x+1 2x+2 x-1 x+1

Huffman Coding Trees Each character has exactly 8 bits Goal: to have a message/file take less space Allow some characters to have shorter bit patterns, but some characters can have longer. Will not have any benefit if each character appears with equal probability. English does not have equal distribution of character occurance. If we let the single bit 1 represent the letter E, then no other character can start with a 1. So some will have to be longer.

The Tree Look at the left pointer as the way to go for a 0 and the right pointer is the way to go for a 1. Take input string of 1’s and 0’s and follow them until hit null pointer, then the character in that node is the character being held. Example: 0 = E 10 = T 110 = P 111 = F =EPFET E T P F

Weighted Tree Each time we have to go to another level, takes time. Want to go down as few times as needed. Have the most frequently used items at the top, least frequently items at the bottom. If we have weights or frequencies of nodes, then we want a tree with minimal external path weight.

Huffman Example Assume the following characters with their relative frequencies. Z K F C U D L E Arrange from smallest to largest. Combine 2 smallest with a parent node with the sum of the 2 frequencies. Replace the 2 values with the sum. Combine the nodes with the 2 smallest values until only one node left.

Huffman Tree Construction Z K F C U D L E E 37 U 42 D 42 L 32 C 2Z2Z 7K7K 24 F

Results LetFreqCodeBitsMess. Len.Old BitsOld Mess. Len. C D E F K L U Z TOTAL:785918

Heap Is a complete binary tree with the heap property –min-heap : All values are less than the child values. –Max-heap: all values are greater than the child values. The values in a heap are partially ordered. There is a relationship between a node’s value and the value of it’s children nodes. Representation: Usually the array based complete binary tree representation.

Building the Heap Several ways to build the heap. As we add each node, or create “a” tree as we get all the data and then “heapify” it. More efficient if we wait until all data is in

Heap ADT class heap{ private: ELEM* Heap; int size; int n; void siftdown(int); public: heap(ELEM*, int, int); int heapsize() const; bool isLeaf(int) const; int leftchild(int) const; int rightchild(int) const; int parent(int) const; void insert(const ELEM); ELEM removemax(); ELEM remove(int); void buildheap();};

Siftdown 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. void heap::buildheap() {for (int i=n/2-1; i>=0; i--) siftdown(i);} void heap::siftdown(int pos){ assert((pos>=0) && (pos<n)); while (!isleaf(pos)) { int j=leftchild(pos); if ((j<(n-1) && key(Heap[j])<key(Heap[j+1]))) j++; // j now has position of child with greater value if (key(Heap[pos])>=key(Heap[j])) return; swap(Heap[pos], Heap[j]); pos=j; } }

Priority Queues A priority queue stores objects and on request, releases the object with the greatest value. Example : scheduling jobs in a multi-tasking operating system. The priority of a job may change, requiring some reordering of the jobs. Implementation: use a heap to store the priority queue. To support priority reordering, delete and re-insert. Need to know index for the object. ELEM heap::remove(int pos) { assert((pos>0) && (pos<n)); swap (Heap[pos], Heap[--n]); if (n!=0) siftdown(pos); return Heap[n]; }