Trees CS-212 Dick Steflik. What is a Tree A tree is a finite set of one or more nodes such that: –There is a specially designated node called the root.

Slides:



Advertisements
Similar presentations
Chapter 12 Binary Search Trees
Advertisements

Comp 122, Spring 2004 Binary Search Trees. btrees - 2 Comp 122, Spring 2004 Binary Trees  Recursive definition 1.An empty tree is a binary tree 2.A node.
Trees Types and Operations
S. Sudarshan Based partly on material from Fawzi Emad & Chau-Wen Tseng
Search Trees: BSTs and B-Trees David Kauchak cs302 Spring 2013.
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.
4.5 AVL Trees  A tree is said to be balanced if for each node, the number of nodes in the left subtree and the number of nodes in the right subtree differ.
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.
Version TCSS 342, Winter 2006 Lecture Notes Priority Queues Heaps.
Heaps & Priority Queues Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
© 2006 Pearson Addison-Wesley. All rights reserved11 A-1 Chapter 11 Trees.
Chapter 12 C Data Structures Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Advanced Tree Data Structures Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Fall 2007CS 2251 Self-Balancing Search Trees Chapter 9.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Marc Smith and Jim Ten Eyck
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.
Chapter 08 Binary Trees and Binary Search Trees © John Urrutia 2013, All Rights Reserved.
1 Search Trees - Motivation Assume you would like to store several (key, value) pairs in a data structure that would support the following operations efficiently.
Data Structures - CSCI 102 Binary Tree In binary trees, each Node can point to two other Nodes and looks something like this: template class BTNode { public:
PRIORITY QUEUES (HEAPS). Queues are a standard mechanism for ordering tasks on a first-come, first-served basis However, some tasks may be more important.
Trees CS212 & CS-240 D.J. Foreman. What is a Tree A tree is a finite set of one or more nodes such that: –There is a specially designated node called.
12-CRS-0106 REVISED 8 FEB 2013 CSG2A3 ALGORITMA dan STRUKTUR DATA.
Chapter 12. Binary Search Trees. Search Trees Data structures that support many dynamic-set operations. Can be used both as a dictionary and as a priority.
S EARCHING AND T REES COMP1927 Computing 15s1 Sedgewick Chapters 5, 12.
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.
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.
Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
Binary SearchTrees [CLRS] – Chap 12. What is a binary tree ? A binary tree is a linked data structure in which each node is an object that contains following.
Starting at Binary Trees
Topic 15 The Binary Search Tree ADT Binary Search Tree A binary search tree (BST) is a binary tree with an ordering property of its elements, such.
 Trees Data Structures Trees Data Structures  Trees Trees  Binary Search Trees Binary Search Trees  Binary Tree Implementation Binary Tree Implementation.
Binary trees -2 Chapter Threaded trees (depth first) Binary trees have a lot of wasted space: the leaf nodes each have 2 null pointers We can.
Lec 15 Oct 18 Binary Search Trees (Chapter 5 of text)
Priority Queue. Priority Queues Queue (FIFO). Priority queue. Deletion from a priority queue is determined by the element priority. Two kinds of priority.
Preview  Graph  Tree Binary Tree Binary Search Tree Binary Search Tree Property Binary Search Tree functions  In-order walk  Pre-order walk  Post-order.
Data Structures – Week #5 Trees (Ağaçlar). December 4, 2015Borahan Tümer, Ph.D.2 Trees (Ağaçlar) Toros GöknarıAvrupa Göknarı.
Week 7 - Friday.  What did we talk about last time?  Trees in general  Binary search trees.
CHAPTER 5 PRIORITY QUEUES (HEAPS) §1 ADT Model Objects: A finite ordered list with zero or more elements. Operations:  PriorityQueue Initialize( int.
Tree Traversals, TreeSort 20 February Expression Tree Leaves are operands Interior nodes are operators A binary tree to represent (A - B) + C.
Binary Trees In computer science, a binary tree is a tree data structure in which each node has at most two children, which are referred to as the left.
David Stotts Computer Science Department UNC Chapel Hill.
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
Binary Tree. Some Terminologies Short review on binary tree Tree traversals Binary Search Tree (BST)‏ Questions.
Binary Search Trees (BST)
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.
Types of Binary Trees Expression Tree A binary tree can store anything where the number ‘2’ comes into picture. In an arithmetic expression: So an arithmetic.
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
Lecture 10COMPSCI.220.FS.T Binary Search Tree BST converts a static binary search into a dynamic binary search allowing to efficiently insert and.
Concepts of Algorithms CSC-244 Unit 19 & 20 Binary Search Tree (BST) Shahid Iqbal Lone Computer College Qassim University K.S.A.
CS 367 Introduction to Data Structures Lecture 8.
Foundation of Computing Systems Lecture 4 Trees: Part I.
1 the BSTree class  BSTreeNode has same structure as binary tree nodes  elements stored in a BSTree are a key- value pair  must be a class (or a struct)
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.
Trees CSIT 402 Data Structures II 1. 2 Why Do We Need Trees? Lists, Stacks, and Queues are linear relationships Information often contains hierarchical.
Chapter 12 – Data Structures
Non Linear Data Structure
Trees Chapter 15.
UNIT III TREES.
Week 6 - Wednesday CS221.
Lecture 22 Binary Search Trees Chapter 10 of textbook
Chapter 22 : Binary Trees, AVL Trees, and Priority Queues
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.
Lec 12 March 9, 11 Mid-term # 1 (March 21?)
CS-240 Dick Steflik D.J. Foreman
Binary Trees, Binary Search Trees
Trees.
Binary Trees, Binary Search Trees
Presentation transcript:

Trees CS-212 Dick Steflik

What is a Tree A tree is a finite set of one or more nodes such that: –There is a specially designated node called the root –The remaining nodes are partitioned into n>0 disjoint sets T 1,..,T n, where each of these sets is a tree. T 1,..,T n are the subtrees of the root.

Examples

Tree Terms Root A B C D E F G H height (h) leaf nodes (exterior nodes) interior nodes A is the parent of B and C B and C are siblings B and C are children of A

height - the number of nodes in the longest path going from the root to the furthest leaf parent - any node in the tree at the next higher level in the tree child - any node in the tree at the next lower level in the tree siblings - any nodes in the tree having a common parent order - the number of children in the node having the largest number of children binary tree - any order 2 tree binary search tree - any binary tree having the search tree property

Things represented as trees Table of Contents Subassembly diagrams Genealogy diagrams Pedigree diagrams Tournament playoffs Graphics representation Organizational charts

Nodal Structure Options If we know the maximum order that an arbitrary tree is supposed to be we could allocate our data content and a child pointer for each possible child Ex suppose max. order = 5 Data child 1 child 2 child 3 child 4 child 5 each node would look like: If our tree has many nodes that have less than 5 children this representation could be very wasteful considering that each child pointer requires 4 bytes of storage. Is there a better, less wasteful representation?

As it turns out, YES there is The lowly order 2 (binary) tree can be used to represent any order n tree. and we can make the statement that: For any general tree, there is an equivalent binary tree To do this we must visualize an order 2 tree differently; instead of as a collection of parents and children we view it as parent, leftmost child and that child’s siblings A BCD Instead of this : A B C D This:

Why do we want to do this? It turns out that order 2 tree have a very nice structure in that there are only two choices to make; Right or Left. This makes it easier to design algorithms for them. To explore this let us look at the problem of creating an algorithm for visiting every node in a tree in some predictable order. This problem is called Traversal and can be accomplished with the following the following algorithm. 1. start at the root and 2. follow all of the left links until you can’t go any farther 3. back-up one node and try going right, if you can repeat steps 2 and 3, if you can’t repeat step 3

Node Structure (Static) typedef struct { Element data; Link left Link right; } Node; typedef struct { int numFree; int numInTree; Link free; Link root; Node Nodes[NUMNODES]; } tree;

Node Structure (Dynamic) typedef node * Tree; struct Node{ element e; Tree left; Tree right; };

Static or Dynamic ? Static –you know the maximum number of nodes not likely to change Dynamic –size of the tree will change frequently –slightly faster than static traversing pointers is faster than calculating addresses for array indexing

Traversal A B C Notice that each node is visited 3 times Were we to print out the node data in the first visit to each node the printout would be : ABC Were we to printout the node data on the second visit to each node the printout would be: BAC Were we to printout the node data on the third visit to each node the printout would be: BCA These are called the: preorder, inorder and postorder traversals respevtively

Pre-order Traversal void preorder( tnode * t) { if (t != NULL) { printf (“ %d “, t -> data ); preorder(t -> left); preorder(t -> right); }

In-order Traversal void inorder( tnode * t) { if (t != NULL) { inorder(t -> left); printf(“ %d “, t -> data ); inorder(t -> right; }

Post-order Traversal void postorder( tnode * t) { if (t != NULL) { postorder(t -> left); postorder(t -> right); printf(“ %d “, t -> data ); }

Notice that... the first node visited on the pre-order traversal ia always the root the left-most node in the tree is the first node on the inorder traversal the last node visited on the inorder traversal is the rightmost node in the tree the last node visited on the postorder traversal is the root Knowing this and given any two traversal paths the tree can be constructed…….

Armed with this information… We should be able to construct the tree that produced any pair of traversal paths

Insertion Tree insert(Tree p, int v) { if (p == NULL) { p = (Tree) malloc(sizeof(struct Node)); p->data = v; p->right = NULL; p->left = NULL; } else if (v data) p->left = insert(p->left,v); else if (v > p->data) p->right = insert(p->right,v); return p; };

search Tree search(Tree p, int v) { if ((p == NULL) || (v == p->data)) { printf("Found\n"); return p; } if (v data) return search(p->left,v); else return search(p->right,v); };

Note: –If the tree is being used to represent a set the search function would be better named isMember( )

Priority Queue BST could be used as a Priority Queue –Needs functions: insert( ) findMin( ) removeMin( ) or findMax( ) removeMax( ) Node with minimum priority is leftmost node Node with maximum priority is rightmost node

Deletion Three cases we need to consider: –V has no children Remove v –V has one child Swap v with child and do 1 –V has 2 children Swap v with successor –leftmost node in right subtree Do case 1 or case 2 to delete

Deletion

Heaps The heap property: –max heap: the largest key is at the root; at each node the keys of the children must be less than the key of the parent –min heap: the smallest key is at the root; the keys of the children must be greater than the key of the parent –used as a priority queue; and the basis for heap sort

Visualize a one dimensional array as a tree as follows (the array contains the keys)

To Find the child or parent i L = (2*i P )+1 i R = (2*i P )+2 i P = (i C -1)/2

Adding a Key Tree is complete (i.e. it fills up in ascending index positions) Must keep track of where end of tree currently is Insert new key at end of tree, then bubble it up to it proper location by comparing to the parent’s key and swapping if necessary This gives O(log 2 n) for each add.

Deleting a key Swap the last key with the root and remove the last key Recursivly push the root down to its proper level by comparing it to its children and swapping with smallest child This gives O(log 2 n) for each deletion

Insuring O(log 2 n) performance The main problem with BST is that its hard to insure optimum performance. –shape of the tree is very dependent on the order the keys were inserted in trees tend to degenerate to varying degrees

The solution - Self-balancing trees AVL Trees Red/Black Trees 2-3 trees trees B-Trees

AVL Trees Height balanced –at every node the allowable difference in height between the right and left subtree is one –an additional piece of data is required balance factor –value = 0 : right and left subtrees are same height –value = 1 : right subtree is one higher –value = -1 : left subtree is one higher –value = 2 or -2 : tree need to be rebalanced

AVL Method Insertion is pretty much like a BST recursive insertion but on the way out (unwinding the recursion) check and adjust the balance factors, if a difference of 2 or -2 is found rebalance the tree by doing an RR, LL, RL or LR rotation

Out of Balance Conditions insertion into left subtree of left child of x called LL (mirror image of RR) fix with a rotateRight insertion into right subtree of right child of x called RR (mirror image of LL) fix with a rotateLeft insertion into left subtree of right child of x called LR (mirror image of RL) fix with a rotateLeft, rotateRight insertion into right subtree of left child of x called RL (mirror image of LR) fix with a rotateRight, rotateLeft

LL k1 k2 k1 A A A B BB C C C Node * rotateLeft(Node * k2) { Node * k1 = k2->left; k2 ->left = k1->right; k1->right = k2; return k1 }

LR k2 k1 A k3 B C D k1 k3 k2 A BC D Node * DoubleRotateLeft( Node * k3) { k3->left = RotateLeft(k3->left); return RotateRight(k3); } k1 k2 A B C k3 D