DATA STRUCTURE SUBMUTTED BY:- MADHU MADHAN Lecturer in computer engg. G.P. MEHAM (ROHTAK)

Slides:



Advertisements
Similar presentations
Linked Lists Geletaw S..
Advertisements

Lists CS 3358.
COMP171 Fall 2005 Lists.
Linked Lists.
DATA STRUCTURES USING C++ Chapter 5
Trees and Binary Trees Become Rich Force Others to be Poor Rob Banks
Linked List
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
Stack and Queue COMP171 Fall Stack and Queue / Slide 2 Stack Overview * Stack ADT * Basic operations of stack n Pushing, popping etc. * Implementations.
Trees Briana B. Morrison Adapted from Alan Eugenio.
Stacks and Queues COMP171 Fall Stack and Queue / Slide 2 Stack Overview * Stack ADT * Basic operations of stack n Pushing, popping etc. * Implementations.
Lists A list is a finite, ordered sequence of data items. Two Implementations –Arrays –Linked Lists.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
CS 104 Introduction to Computer Science and Graphics Problems Data Structure & Algorithms (4) Data Structures 11/18/2008 Yang Song.
Trees COMP53 Oct 31, What is a Tree? A tree is an abstract model of a hierarchical structure A tree consists of nodes with a parent-child relation.
Trees1 Part-C Trees Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery.
Linked Lists Spring Linked Lists / Slide 2 List Overview * Linked lists n Abstract data type (ADT) * Basic operations of linked lists n Insert,
Chapter 12 Data Structure Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Trees.
Make Money Fast! Stock Fraud Apply shortcuts Bank Robbery Just For Laughs Trees This one is cool eITnotes.com For more notes and topics visit:
Trees CSCI 3333 Data Structures. Acknowledgement  Dr. Bun Yue  Mr. Charles Moen  Dr. Wei Ding  Ms. Krishani Abeysekera  Dr. Michael Goodrich  Dr.
CS Data Structures Chapter 5 Trees. Chapter 5 Trees: Outline  Introduction  Representation Of Trees  Binary Trees  Binary Tree Traversals 
Lecture 10 Trees –Definiton of trees –Uses of trees –Operations on a tree.
Binary Trees, Binary Search Trees RIZWAN REHMAN CENTRE FOR COMPUTER STUDIES DIBRUGARH UNIVERSITY.
Chapter 5 – Dynamic Data Structure Part 2: Linked List DATA STRUCTURES & ALGORITHMS Teacher: Nguyen Do Thai Nguyen
Stack Overview. Stack Stack ADT Basic operations of stack – Pushing, popping etc. Implementations of stacks using – array – linked list.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Data Structures & Algorithm Analysis Muhammad Hussain Mughal Trees. Binary Trees. Reading: Chap.4 ( ) Weiss.
Review 1 Queue Operations on Queues A Dequeue Operation An Enqueue Operation Array Implementation Link list Implementation Examples.
Trees1 Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery © 2013 Goodrich, Tamassia, Goldwasser.
IKI 10100I: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100I: Data.
CH 7. TREES ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN C++, GOODRICH, TAMASSIA AND MOUNT (WILEY.
24 January Trees CSE 2011 Winter Trees Linear access time of linked lists is prohibitive  Does there exist any simple data structure for.
CH 7 : TREE ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN C++, GOODRICH, TAMASSIA AND MOUNT (WILEY.
BINARY TREES Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary.
© 2004 Goodrich, Tamassia Trees1 Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery.
Data Structure & Algorithms
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture13.
TREE Ahsan Ahmed College of Computer and Information Science Majma’ah University 1.
DATA STRUCURES II CSC QUIZ 1. What is Data Structure ? 2. Mention the classifications of data structure giving example of each. 3. Briefly explain.
What is a Tree? Formally, we define a tree T as a set of nodes storing elements such that the nodes have a parent-child relationship, that satisfies the.
Elementary Data Structures
CSCE 3110 Data Structures & Algorithm Analysis
Trees 5/2/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser,
Trees 5/10/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser,
Unit – I Lists.
Data Structure By Amee Trivedi.
Chapter 12 – Data Structures
Lecture 1 (UNIT -4) TREE SUNIL KUMAR CIT-UPES.
Trees Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery
Trees Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery Trees
Lists CS 3358.
Trees 二○一八年八月二十六日 Part-C Trees Trees.
Binary Trees, Binary Search Trees
Trees 9/21/2018 9:58 PM Trees this is a tree Trees.
CMSC 341 Lecture 5 Stacks, Queues
COSC2100: Data Structures and Algorithms
Trees Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery
Trees Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery
Trees Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery
Elementary Data Structures
Week nine-ten: Trees Trees.
Trees Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery Trees
Trees "A tree may grow a thousand feet tall, but its leaves will return to its roots." -Chinese Proverb CLRS, Section 10.4.
Trees Palestine Gaza West Bank 48 Stolen Land Trees Trees
Binary Trees, Binary Search Trees
CS210- Lecture 9 June 20, 2005 Announcements
Trees Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery
Trees.
NATURE VIEW OF A TREE leaves branches root. NATURE VIEW OF A TREE leaves branches root.
Presentation transcript:

DATA STRUCTURE SUBMUTTED BY:- MADHU MADHAN Lecturer in computer engg. G.P. MEHAM (ROHTAK)

ARRAY

Arrays An array is a collection of data elements that are of the same type (e.g., a collection of integers, collection of characters, collection of doubles).

Arrays 1-dimensional array. 3-dimensional array (3rd dimension is the day). Oct 14 Oct 15 Oct 16

Array Applications Given a list of test scores, determine the maximum and minimum scores. Read in a list of student names and rearrange them in alphabetical order (sorting). Given the height measurements of students in a class, output the names of those students who are taller than average.

Array Declaration Syntax: <type> <arrayName>[<array_size>] Ex. int Ar[10]; The array elements are all values of the type <type>. The size of the array is indicated by <array_size>, the number of elements in the array. <array_size> must be an int constant or a constant expression. Note that an array can have multiple dimensions.

Array Declaration // array of 10 uninitialized ints int Ar[10]; -- Ar 4 5 6 3 2 8 9 7 1 1 2 3 4 5

Subscripting Declare an array of 10 integers: int Ar[10]; // array of 10 ints To access an individual element we must apply a subscript to array named Ar. A subscript is a bracketed expression. The expression in the brackets is known as the index. First element of array has index 0. Ar[0] Second element of array has index 1, and so on. Ar[1], Ar[2], Ar[3],… Last element has an index one less than the size of the array. Ar[9] Incorrect indexing is a common error.

Subscripting // array of 10 uninitialized ints int Ar[10]; Ar[3] = 1; int x = Ar[3]; 1 -- -- 1 Ar 4 5 6 3 2 8 9 7 Ar[4] Ar[5] Ar[6] Ar[3] Ar[0] Ar[2] Ar[8] Ar[9] Ar[7] Ar[1]

Array Initialization Ex. 4 int Ar[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; Ar[3] = -1; 8 7 6 9 Ar 4 3 2 5 1 6 -1 8 7 -1 9 Ar 4 3 2 5 1 6

Program with Arrays int main() { int values[5]= {11,1,3,6,10}; for (int i = 1; i < 5; i++) values[i] = values[i] + values[i-1]; } values[0] = values[1] + values[4];

Stack Overview Stack Basic operations of stack Pushing, popping etc. Implementations of stacks using array linked list

The Stack A stack is a list with the restriction that insertions and deletions can only be performed at the top of the list The other end is called bottom Fundamental operations: Push: Equivalent to an insert Pop: Deletes the most recently inserted element Top: Examines the most recently inserted element

Stacks are less flexible but are more efficient and easy to implement Stacks are known as LIFO (Last In, First Out) lists. The last element inserted will be the first to be retrieved

Push and Pop Primary operations: Push and Pop Push Pop Add an element to the top of the stack Pop Remove the element at the top of the stack empty stack push an element push another pop top B top top A A A top

Implementation of Stacks Any list implementation could be used to implement a stack Arrays (static: the size of stack is given initially) Linked lists (dynamic: never become full) We will explore implementations based on array and linked list Let’s see how to use an array to implement a stack first

Array Implementation Need to declare an array size ahead of time Associated with each stack is TopOfStack for an empty stack, set TopOfStack to -1 Push (1)   Increment TopOfStack by 1. (2)   Set Stack[TopOfStack] = X Pop (1)   Set return value to Stack[TopOfStack] (2)   Decrement TopOfStack by 1 These operations are performed in very fast constant time

Push Stack void Push(const double x); Push an element onto the stack If the stack is full, print the error information. Note top always represents the index of the top element. After pushing an element, increment top. void Stack::Push(const double x) { if (IsFull()) cout << "Error: the stack is full." << endl; else values[++top] = x; }

Pop Stack double Pop() Pop and return the element at the top of the stack If the stack is empty, print the error information. (In this case, the return value is useless.) Don’t forgot to decrement top double Stack::Pop() { if (IsEmpty()) { cout << "Error: the stack is empty." << endl; return -1; } else { return values[top--];

Stack Top double Top() Return the top element of the stack Unlike Pop, this function does not remove the top element double Stack::Top() { if (IsEmpty()) { cout << "Error: the stack is empty." << endl; return -1; } else return values[top];

Queue Overview Queue Basic operations of queue Implementation of queue Enqueuing, dequeuing etc. Implementation of queue Array Linked list

Queue Like a stack, a queue is also a list. However, with a queue, insertion is done at one end, while deletion is performed at the other end. Accessing the elements of queues follows a First In, First Out (FIFO) order. Like customers standing in a check-out line in a store, the first customer in is the first customer served.

Enqueue and Dequeue Primary queue operations: Enqueue and Dequeue Like check-out lines in a store, a queue has a front and a rear. Enqueue Insert an element at the rear of the queue Dequeue Remove an element from the front of the queue Insert (Enqueue) Remove (Dequeue) front rear

Implementation of Queue Just as stacks can be implemented as arrays or linked lists, so with queues. Dynamic queues have the same advantages over static queues as dynamic stacks have over static stacks

List Overview Linked lists Basic operations of linked lists Insert, find, delete, print, etc. Variations of linked lists Doubly linked lists

Linked Lists A linked list is a series of connected nodes B C  Head A linked list is a series of connected nodes Each node contains at least A piece of data (any type) Pointer to the next node in the list Head: pointer to the first node The last node points to NULL node A data pointer

A Simple Linked List Class We use two classes: Node and List Declare Node class for the nodes data: double-type data in this example next: a pointer to the next node in the list class Node { public: double data; // data Node* next; // pointer to next };

A Simple Linked List Class Declare List, which contains head: a pointer to the first node in the list. Since the list is empty initially, head is set to NULL Operations on List class List { public: List(void) { head = NULL; } // constructor ~List(void); // destructor bool IsEmpty() { return head == NULL; } Node* InsertNode(int index, double x); int FindNode(double x); int DeleteNode(double x); void DisplayList(void); private: Node* head; };

A Simple Linked List Class Operations of List IsEmpty: determine whether or not the list is empty InsertNode: insert a new node at a particular position FindNode: find a node with a given value DeleteNode: delete a node with a given value DisplayList: print all the nodes in the list

Inserting a new node Node* InsertNode(int index, double x) Steps Insert a node with data equal to x after the index’th elements. (i.e., when index = 0, insert the node as the first element; when index = 1, insert the node after the first element, and so on) If the insertion is successful, return the inserted node. Otherwise, return NULL. (If index is < 0 or > length of the list, the insertion will fail.) Steps Locate index’th element Allocate memory for the new node Point the new node to its successor Point the new node’s predecessor to the new node index’th element newNode

Inserting a new node Possible cases of InsertNode Insert into an empty list Insert in front Insert at back Insert in middle But, in fact, only need to handle two cases Insert as the first node (Case 1 and Case 2) Insert in the middle or at the end of the list (Case 3 and Case 4)

Deleting a node Steps Like InsertNode, there are two special cases int DeleteNode(double x) Delete a node with the value equal to x from the list. If such a node is found, return its position. Otherwise, return 0. Steps Find the desirable node (similar to FindNode) Release the memory occupied by the found node Set the pointer of the predecessor of the found node to the successor of the found node Like InsertNode, there are two special cases Delete first node Delete the node in middle or at the end of the list

Variations of Linked Lists Circular linked lists The last node points to the first node of the list How do we know when we have finished traversing the list? (Tip: check if the pointer of the current node is equal to the head.) A B C Head

Variations of Linked Lists Doubly linked lists Each node points to not only successor but the predecessor There are two NULL: at the first and last nodes in the list Advantage: given a node, it is easy to visit its predecessor. Convenient to traverse lists backwards A B C   Head

Array versus Linked Lists Linked lists are more complex to code and manage than arrays, but they have some distinct advantages. Dynamic: a linked list can easily grow and shrink in size. We don’t need to know how many nodes will be in the list. They are created in memory as needed. In contrast, the size of a C++ array is fixed at compilation time. Easy and fast insertions and deletions To insert or delete an element in an array, we need to copy to temporary variables to make room for new elements or close the gap caused by deleted elements. With a linked list, no need to move other nodes. Only need to reset some pointers.

Trees and Binary Trees Become Rich Force Others to be Poor Rob Banks Stock Fraud The class notes are a compilation and edition from many sources. The instructor does not claim intellectual property or ownership of the lecture notes.

What is a Tree A tree is a finite nonempty set of elements. It is an abstract model of a hierarchical structure. consists of nodes with a parent-child relation. Applications: Organization charts File systems Programming environments Computers”R”Us Sales R&D Manufacturing Laptops Desktops US International Europe Asia Canada

Tree Terminology subtree Subtree: tree consisting of a node and its descendants Root: node without parent (A) Siblings: nodes share the same parent Internal node: node with at least one child (A, B, C, F) External node (leaf ): node without children (E, I, J, K, G, H, D) Ancestors of a node: parent, grandparent, grand-grandparent, etc. Descendant of a node: child, grandchild, grand-grandchild, etc. Depth of a node: number of ancestors Height of a tree: maximum depth of any node (3) Degree of a node: the number of its children Degree of a tree: the maximum number of its node. A B D C G H E F I J K subtree

Tree Properties Property Value Number of nodes Height Root Node Leaves Interior nodes Ancestors of H Descendants of B Siblings of E Right subtree of A Degree of this tree A B C D G E F I H

Trees Every tree node: object – useful information children – pointers to its children Data Data  Data  Data  Data  Data  Data 

A Tree Representation  B D A C E F A node is represented by an object storing Element Parent node Sequence of children nodes  B A D F C E B D A C E F

Left Child, Right Sibling Representation Data Left Child Right Sibling A B C D E F G H I J K L

Tree Traversal Two main methods: Recursive definition Preorder: Postorder Recursive definition Preorder: visit the root traverse in preorder the children (subtrees) traverse in postorder the children (subtrees)

Preorder Traversal Algorithm preOrder(v) visit(v) A traversal visits the nodes of a tree in a systematic manner In a preorder traversal, a node is visited before its descendants Application: print a structured document Algorithm preOrder(v) visit(v) for each child w of v preorder (w) Become Rich 1. Motivations 3. Success Stories 2. Methods 2.1 Get a CS PhD 2.2 Start a Web Site 1.1 Enjoy Life 1.2 Help Poor Friends 2.3 Acquired by Google 1 2 3 5 4 6 7 8 9

Postorder Traversal Algorithm postOrder(v) for each child w of v In a postorder traversal, a node is visited after its descendants Application: compute space used by files in a directory and its subdirectories Algorithm postOrder(v) for each child w of v postOrder (w) visit(v) cs16/ homeworks/ todo.txt 1K programs/ DDR.java 10K Stocks.java 25K h1c.doc 3K h1nc.doc 2K Robot.java 20K 9 3 1 7 2 4 5 6 8

Binary Tree A binary tree is a tree with the following properties: Each internal node has at most two children (degree of two) The children of a node are an ordered pair We call the children of an internal node left child and right child Alternative recursive definition: a binary tree is either a tree consisting of a single node, OR a tree whose root has an ordered pair of children, each of which is a binary tree Applications: arithmetic expressions decision processes searching A B C D E F G H I

Examples of the Binary Tree Skewed Binary Tree E C D 5 A B C G E I D H F Complete Binary Tree 1 2 3 4

Differences Between A Tree and A Binary Tree The subtrees of a binary tree are ordered; those of a tree are not ordered. A B A B Are different when viewed as binary trees. Are the same when viewed as trees.

Data Structure for Binary Trees A node is represented by an object storing Element Parent node Left child node Right child node  B A D C E B D A C E

Maximum Number of Nodes in a Binary Tree The maximum number of nodes on depth i of a binary tree is 2i, i>=0. The maximum nubmer of nodes in a binary tree of height k is 2k+1-1, k>=0. Prove by induction.

Full Binary Tree Height 3 full binary tree. A full binary tree of a given height k has 2k+1–1 nodes. Height 3 full binary tree.

Node Number Properties 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Parent of node i is node i / 2, unless i = 1. Node 1 is the root and has no parent.

Labeling Nodes In A Full Binary Tree Label the nodes 1 through 2k+1 – 1. Label by levels from top to bottom. Within a level, label from left to right. 1 2 3 4 6 5 7 8 9 10 11 12 13 14 15

Node Number Properties 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Left child of node i is node 2i, unless 2i > n, where n is the number of nodes. If 2i > n, node i has no left child.

Node Number Properties 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Right child of node i is node 2i+1, unless 2i+1 > n, where n is the number of nodes. If 2i+1 > n, node i has no right child.

Full binary tree of depth 3 Complete Binary Trees A labeled binary tree containing the labels 1 to n with root 1, branches leading to nodes labeled 2 and 3, branches from these leading to 4, 5 and 6, 7, respectively, and so on. A binary tree with n nodes and level k is complete iff its nodes correspond to the nodes numbered from 1 to n in the full binary tree of level k. 1 2 3 7 5 11 4 10 6 9 8 15 14 13 12 Full binary tree of depth 3 1 2 3 7 5 9 4 8 6 Complete binary tree

Binary Tree Traversals Let l, R, and r stand for moving left, visiting the node, and moving right. There are six possible combinations of traversal lRr, lrR, Rlr, Rrl, rRl, rlR Adopt convention that we traverse left before right, only 3 traversals remain lRr, lrR, Rlr inorder, postorder, preorder

Inorder Traversal Algorithm inOrder(v) if isInternal (v) In an inorder traversal a node is visited after its left subtree and before its right subtree Algorithm inOrder(v) if isInternal (v) inOrder (leftChild (v)) visit(v) inOrder (rightChild (v)) 3 1 2 5 6 7 9 8 4

THANK YOU