Data Structures. September 28



Similar documents
Converting a Number from Decimal to Binary

Binary Search Trees (BST)

Ordered Lists and Binary Trees

Data Structure with C

Binary Search Trees CMPSC 122

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

DATA STRUCTURES USING C

Data Structures and Algorithms

Binary Search Trees. A Generic Tree. Binary Trees. Nodes in a binary search tree ( B-S-T) are of the form. P parent. Key. Satellite data L R

From Last Time: Remove (Delete) Operation

ECE 250 Data Structures and Algorithms MIDTERM EXAMINATION /5:15-6:45 REC-200, EVI-350, RCH-106, HH-139

Chapter 14 The Binary Search Tree

The ADT Binary Search Tree

Data Structures and Algorithms(5)

Data Structures Using C++ 2E. Chapter 5 Linked Lists

Data Structure [Question Bank]

TREE BASIC TERMINOLOGIES

Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

Heaps & Priority Queues in the C++ STL 2-3 Trees

PES Institute of Technology-BSC QUESTION BANK

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

Analysis of Algorithms I: Binary Search Trees

The following themes form the major topics of this chapter: The terms and concepts related to trees (Section 5.2).

Home Page. Data Structures. Title Page. Page 1 of 24. Go Back. Full Screen. Close. Quit

A binary search tree is a binary tree with a special property called the BST-property, which is given as follows:

Big Data and Scripting. Part 4: Memory Hierarchies

Binary Heap Algorithms

MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push)

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

5. A full binary tree with n leaves contains [A] n nodes. [B] log n 2 nodes. [C] 2n 1 nodes. [D] n 2 nodes.

A binary heap is a complete binary tree, where each node has a higher priority than its children. This is called heap-order property

10CS35: Data Structures Using C

Algorithms Chapter 12 Binary Search Trees

Binary Search Trees. Data in each node. Larger than the data in its left child Smaller than the data in its right child

Learning Outcomes. COMP202 Complexity of Algorithms. Binary Search Trees and Other Search Trees

root node level: internal node edge leaf node Data Structures & Algorithms McQuain

Output: struct treenode{ int data; struct treenode *left, *right; } struct treenode *tree_ptr;

CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 221] edge. parent

Binary Trees and Huffman Encoding Binary Search Trees

Any two nodes which are connected by an edge in a graph are called adjacent node.

Data Structures, Practice Homework 3, with Solutions (not to be handed in)

Exam study sheet for CS2711. List of topics

Binary Heaps. CSE 373 Data Structures

Data Structures. Level 6 C Module Descriptor

Binary Heaps * * * * * * * / / \ / \ / \ / \ / \ * * * * * * * * * * * / / \ / \ / / \ / \ * * * * * * * * * *

Algorithms and Data Structures

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

6 March Array Implementation of Binary Trees

GRAPH THEORY LECTURE 4: TREES

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Sample Questions Csci 1112 A. Bellaachia

Lecture Notes on Binary Search Trees

Unordered Linked Lists

CSE 326, Data Structures. Sample Final Exam. Problem Max Points Score 1 14 (2x7) 2 18 (3x6) Total 92.

Data Structure and Algorithm I Midterm Examination 120 points Time: 9:10am-12:10pm (180 minutes), Friday, November 12, 2010

Cpt S 223. School of EECS, WSU

Chapter 8: Binary Trees

Outline BST Operations Worst case Average case Balancing AVL Red-black B-trees. Binary Search Trees. Lecturer: Georgy Gimel farb

How To Create A Tree From A Tree In Runtime (For A Tree)

B-Trees. Algorithms and data structures for external memory as opposed to the main memory B-Trees. B -trees

Full and Complete Binary Trees

Data Structures Fibonacci Heaps, Amortized Analysis

Parallelization: Binary Tree Traversal

Linked List as an ADT (cont d.)

Java Software Structures

Previous Lectures. B-Trees. External storage. Two types of memory. B-trees. Main principles

CSE 326: Data Structures B-Trees and B+ Trees

INTERNATIONAL JOURNAL OF PURE AND APPLIED RESEARCH IN ENGINEERING AND TECHNOLOGY

International Journal of Software and Web Sciences (IJSWS)

Atmiya Infotech Pvt. Ltd. Data Structure. By Ajay Raiyani. Yogidham, Kalawad Road, Rajkot. Ph : ,

Lecture Notes on Binary Search Trees

Algorithms and Data Structures Written Exam Proposed SOLUTION

A TOOL FOR DATA STRUCTURE VISUALIZATION AND USER-DEFINED ALGORITHM ANIMATION

Algorithms and Data S tructures Structures Stack, Queues, and Applications Applications Ulf Leser

Data Structures Using C++

Persistent Binary Search Trees

Data Structures. Jaehyun Park. CS 97SI Stanford University. June 29, 2015

Data Structures Using C++ 2E. Chapter 5 Linked Lists

Structural Design Patterns Used in Data Structures Implementation

Binary Search Trees. basic implementations randomized BSTs deletion in BSTs

S. Muthusundari. Research Scholar, Dept of CSE, Sathyabama University Chennai, India Dr. R. M.

M-way Trees and B-Trees

EE602 Algorithms GEOMETRIC INTERSECTION CHAPTER 27

Operations: search;; min;; max;; predecessor;; successor. Time O(h) with h height of the tree (more on later).

ER E P M A S S I CONSTRUCTING A BINARY TREE EFFICIENTLYFROM ITS TRAVERSALS DEPARTMENT OF COMPUTER SCIENCE UNIVERSITY OF TAMPERE REPORT A

Exercises Software Development I. 11 Recursion, Binary (Search) Trees. Towers of Hanoi // Tree Traversal. January 16, 2013

Data Structures UNIT III. Model Question Answer

To My Parents -Laxmi and Modaiah. To My Family Members. To My Friends. To IIT Bombay. To All Hard Workers

Data Structures and Algorithm Analysis (CSC317) Intro/Review of Data Structures Focus on dynamic sets

EE2204 DATA STRUCTURES AND ALGORITHM (Common to EEE, EIE & ICE)

Motivation Suppose we have a database of people We want to gure out who is related to whom Initially, we only have a list of people, and information a

CS711008Z Algorithm Design and Analysis

Data Structures and Data Manipulation

Why Use Binary Trees?

Algorithms and Data Structures

Binary Search Trees. Ric Glassey

Alex. Adam Agnes Allen Arthur

Algorithms and data structures

Glossary of Object Oriented Terms

2. (a) Explain the strassen s matrix multiplication. (b) Write deletion algorithm, of Binary search tree. [8+8]

Transcription:

Data Structures September 28 1

Hierachicalstructures: Trees 2

Objectives Discuss the following topics: Trees, Binary Trees, and Binary Search Trees Implementing Binary Trees Tree Traversal Searching a Binary Search Tree Insertion Deletion 3

Objectives (continued) Discuss the following topics: Heaps Balancing a Tree Self-Adjusting Trees 4

Trees, Binary Trees, and Binary Search Trees A treeis a data type that consists of nodes and arcs These trees are depicted upside down with the rootat the top and the leaves(terminal nodes) at the bottom The rootis a node that has no parent; it can have only child nodes Leaves have no children (their children are null) 5

Trees, Binary Trees, and Binary Search Trees (continued) Each node has to be reachable from the root through a unique sequence of arcs, called a path The number of arcs in a path is called the length of the path The levelof a node is the length of the path from the root to the node plus 1, which is the number of nodes in the path The heightof a nonempty tree is the maximum level of a node in the tree 6

Trees, Binary Trees, and Binary Search Trees (continued) Figure 6-1 Examples of trees 7

Trees, Binary Trees, and Binary Search Trees (continued) Figure 6-2 Hierarchical structure of a university shown as a tree 8

Trees: abstract/mathematical important, great number of varieties Trees (adt adt) terminology (knoop, wortel, vader, kind) node/vertex, root, father/parent, child (non) directed (non) orderly binary trees (left right) full (sometimes called decision trees, see Drozdek), complete (all levels are filled, except the last one) categorization structure number of children (binary, B-boom) height of subtrees (AVL-, B-trees) compleet (heap) Location of keys search tree, heap 9

^ 0 1 thur 16 ζ 1 ζ 2 v ζ 3 A 0 B 0 1 C 1 D mon tues fri sat wed sun 7 12 5 6 10 2 expression code bst 4 2 heap c s a a e r t t a l trie e k expr term fact a expr * term fact a syntax term * fact b sat tues fri mon sun thur B-tree (2,3 tree) wed 10

RecallDefinitionof Tree 1. Anemptystructureis a tree 2. Ift1,..., tkare disjoint trees, thenthe structurewhoseroot has as itschildrenthe rootsof t1,...,tkis alsoa tree 3. Onlystructuresgeneratedbyrule1 and 2 are trees Alternatively: a connected graph which contains nocyclesis a tree 11

Equivalent statements (seeφ1) Let T begraphwithn verticesthenthe following are equivalent: a) T is a tree ( = nocyclesand connected) b) T containsnocycles, and has n-1 edges c) T is connected, and has n-1 edges d) T is connected, and everyedgeis a bridge e) Anytwoverticesare connectedbyexactlyone path f) T containsnocycles, butthe additionof anynew edge creates exactly one circuit (cycle with no repeated edges). 12

Trees, Binary Trees, and Binary Search Trees (continued) An orderly treeiswhere all elements are stored according to some predetermined criterion of ordering Figure 6-3 Transforming (a) a linked list into (b) a tree 13

Binary Trees A binary treeis a tree whose nodes have two children (possibly empty), and each child is designated as either a left child or a right child Figure 6-4 Examples of binary trees 14

Binary Trees In a complete binary tree, all the nodes at all levels have two children except the last level. A decision treeis a binary tree in which all nodes have either zero or two nonempty children incomplete Binary tree Complete Binary tree Dutch: compleet) The more common def Decision tree (Dutch: vol) complete Tree (Drozdek def) 15

Remark on definition of Complete Binary Tree DrozdekPage218 uses the following definition: a complete binary tree is a binary tree of which all non-terminal nodes have both their children, and all leaves are at the same level The more common definition is as follows: A complete binary tree is a binary tree in which every level, except possibly the last, is completed filled, and all nodes are as far left as posssible

Binary Trees At level i in binarytree at most 2 i-1 nodes For non-empty binary tree whose nonterminal nodes(i.e., a full binary tree) have exactly two nonemptychildren: #of leaves= 1+#nonterminal nodes In a Drozdek-complete tree: # of nodes= 2 height -1; oneway toseethisis tousethe statement #of leaves = 1+#nonterminal nodes; anotherwayis tocounthowmany nodesthereare in eachlevel and thensum the geometric progression; 18

Binary Trees Figure 6-5 Adding a leaf to tree (a), preserving the relation of the number of leaves to the number of nonterminal nodes (b) 19

ADT BinaryTree (more explicitly) createbinarytree() //creates an empty binary tree createbinary(rootitem) // creates a one-node bin tree whose root contains rootitem createbinary(rootitem, lefttree, righttree) //createsa bin tree whoseroot contains rootitem //and has lefttree and righttree, respectively, as its left and right subtrees destroybinarytree()// destroys a binary tree rootdata() // returns the data portionof the root of a nonemptybinarytree setrootdata(newitem) // replacesthe thedata portionof the root of a //nonemptybin tree withnewitem. Ifthe bin tree is empty, however, //createsa root node whosedata portionis newitemand insertsthe new //node into the tree attachleft(newitem, success)// attaches a left child containing newitem to //the root of a binarytree. Successindicateswhetherthe operationwas //successful. attachright(newitem, success) // ananlogous to attachleft 20

ADT BinaryTree (continued) attachleftsubtree(lefttree, success) // AttachesleftTreeas the leftsubtree tothe root of a bin tree. Successindicateswhetherthe operationwas successful. attachrightsubtree(righttree, success) // analogous to attachleftsubtree detachleftsubtree(lefttree, success) // detachesthe leftsubtree of a bin tree sroot and retainsitin lefttree. Successindicateswhetherthe op was successful. detachrightsubtree(righttree, success) // similar to detachleftsubtree leftsubtree() // Returns, but does not detach, the left subtree of a bin tree s root rightsubtree() // analogous to leftsubtree preordertraverse(visit) // traversesa binarytree in preorder and callsthe function visit once for each node inordertraverse(visit) // analogous: inorder postordertraverse(visit) // analogous: postorder 21

Implementing Binary Trees Binary trees can be implemented in at least two ways: As arrays As linked structures To implement a tree as an array, a node is declared as an object with an information field and two reference fields 22

Implementing Binary Trees (continued) root free 0 8 Can do for complete binary trees; A[i] with children A[2i] and A[2i+1]. Parent of A[i] is A[i div 2]. Figure 6-7 Array representation of the tree in Figure 6.6c 23

Implementing Binary Trees (continued) Can do array for complete binary trees; Level order storage; A[i] with children A[2i] and A[2i+1]. Parent of A[i] is A[i div 2]: 1 2 3 MaxNode... Heapsort Also for trees of max degree k (at most k children) 33

Binary Tree C++ template <class T> template struct TreeNode { T info; TreeNode<T> *left, * right; int tag // a.o. For threading }; constructor TreeNode ( const T& i, TreeNode<T> *left = NULL, TreeNode<T> *right = NULL ) : info(i) { left = l; right = r; tag = 0; } default constructor of type T See the next slide for the proof of concept; type T=int, is hardwired 25

The programmed ADT Binary Tree (refers to slide 20, 21: ADT Binary Tree) not parametrized: itemtype = int // Impl. // ADT // Client 26

Drozdek Does not showhow to implement Generic Binary Tree 27

bst 28

bst 29

Traversal of Binary Trees 30

Traversal of Binary Trees 31

Traversalsof BinaryTrees Is the process of visiting each node (precisely once) in a systematic way(visiting has technical meaning, a visit can possibly write tothe node, orchangethe structureof the tree, soyouneedtodo itpreciselyonceforeachnode; youcan pass by a node manytimeswhenare onlyreading, forinstance) Why? Get info, updates Check for structural properties, updating Definitely can be extended to graphs(with cycles)! Methods: Depthfirst(recursivelyoriterativelywithstacks): preorder (VLR), inorder(symmetric)-lvr, postorder (LRV) in level order (breadthfirst) --queues 32

Traversalsof BinaryTrees Recursively Iteratively: stacks(depth First) Queues forbreadthfirst Threaded Trees Tree Transformation(e.g., Morris) 33

Tree Traversal: breadth-first Breadth-first traversalis visiting each node starting from the lowest (or highest) level and moving down (or up) level by level, visiting nodes on each level from left to right (or from right to left) 34

Tree Traversal: breadth-first 35

Depth-First Traversal Depth-first traversalproceeds as far as possible to the left (or right), then backs up until the first crossroad, goes one step to the right (or left), and again as far as possible to the left (or right) V Visiting a node L Traversing the left subtree R Traversing the right subtree 36 36

Depth-First Traversal 37

InorderTree Traversal 38

39

S.create(); Preorder Traversal iterative usesa stack S.push(root); while(not S.isEmpty()) { current = S.pop() // a retrieving pop while(current NULL) { visit(current); S.push(current-> right); current = current-> left }// end while 40 }// end while

Preorder Traversal iterative 41

StacklessDepth-First Traversal Threadsare references to the predecessor and successor of the node according to an inorder traversal Trees whose nodes use threads are called threaded trees 42

A threaded tree; an inorder traversal s path in a threaded tree with Right successors only Successor (right Pointer) 43

A threaded tree; right pointers: successors; left pointers: predecessors Successor (right Pointer) Predecessor (left Pointer) 44

MorrisInOrder () while not finished if node has NO left descendant visit it; go to the right; else make this node the right child of the rightmost node in its left descendant; go to this left descendant Traversal Through Tree Transformation 45

Traversal Through Tree Transformation 46

Traversal Through Tree Transformation 47 Figure 6-20 Implementation of the Morris algorithm for inorder traversal

Binary Search Trees Figure 6-6 Examples of binary search trees 48

Searching a Binary Search Tree (continued) The internal path length (IPL)is the sum of all path lengths of all nodes It is calculated by summing Σ(i 1)l i over all levels i, where l i is the number of nodes on level I A depth of a node in the tree is determined by the path length An average depth, called an average path length, is given by the formula IPL/n, which depends on the shape of the tree 49

Insertion Figure 6-22 Inserting nodes into binary search trees 50

Insertion (continued) Figure 6-23 Implementation of the insertion algorithm 51

Insertion (continued) Figure 6-25 Inserting nodes into a threaded tree 52

Deletion in BSTs There are three cases of deleting a node from the binary search tree: The node is a leaf; it has no children The node has one child The node has two children 53

Deletion (continued) Figure 6-26 Deleting a leaf Figure 6-27 Deleting a node with one child 54

Deletion by Merging Making one tree out of the two subtreesof the node and then attaching it to the node s parent is called deleting by merging Figure 6-28 Summary of deleting by merging 55

Deletion by Copying If the node has two children, the problem can be reduced to: The node is a leaf The node has only one nonempty child Solution: replace the key being deleted with its immediate predecessor (or successor) A key s predecessor is the key in the rightmost node in the left subtree 56