The tree data structure. Trees COL 106. Amit Kumar Shweta Agrawal. Acknowledgement :Many slides are courtesy Douglas Harder, UWaterloo

Similar documents
11 TREES DATA STRUCTURES AND ALGORITHMS IMPLEMENTATION & APPLICATIONS IMRAN IHSAN ASSISTANT PROFESSOR, AIR UNIVERSITY, ISLAMABAD

Trees. Data structures and Algorithms. Make Money Fast! Bank Robbery. Stock Fraud. Ponzi Scheme

Trees. 9/21/2007 8:11 AM Trees 1

Trees and Binary Trees

Unit 1 (9Hrs) Trees. Mahesh Sanghavi & Deepali Pawar Department of Computer Engineering, SNJB s KBJ College of Engineering, Chandwad, India

Stock Fraud. Nancy Amato. Parasol Lab, Dept. CSE, Texas A&M University

Data Structures. Trees, Binary trees & Binary Search Trees

Trees. Make Money Fast! Bank Robbery. Ponzi Scheme. Stock Fraud. 02/06/2006 Trees 1

Tree. A path is a connected sequence of edges. A tree topology is acyclic there is no loop.

Trees. Carlos Moreno uwaterloo.ca EIT

Trees. Make Money Fast! Bank Robbery. Ponzi Scheme. Stock Fraud. 1/18/2005 4:17 AM Trees 1

singly and doubly linked lists, one- and two-ended arrays, and circular arrays.

Elementary Data Structures. Stacks, Queues, & Lists Amortized analysis Trees

Trees. Make Money Fast! Bank Robbery. Ponzi Scheme. Stock Fraud Goodrich, Tamassia, Goldwasser Trees

Trees. Make Money Fast! Bank Robbery. Stock Fraud. Ponzi Scheme Goodrich, Tamassia. Trees 1

DATA STRUCTURES USING C

Data Structures and Algorithms. Trees

tree nonlinear Examples

Trees. Make Money Fast! Bank Robbery. Stock Fraud. Ponzi Scheme. Trees Goodrich, Tamassia

Topic 14. The BinaryTree ADT

Trees 3/19/14. Mammal. Dog Pig Cat

OUTLINE. General Trees (Ch. 7.1) Binary Trees (Ch. 7.3) Tree Traversals (Ch. 7.2)

Binary trees. Binary trees. Binary trees

Outline. Definitions Traversing trees Binary trees

Todays Lecture. Assignment 2 deadline: You have 5 Calendar days to complete.

Computer Science 210 Data Structures Siena College Fall Topic Notes: Trees

Trees. (Trees) Data Structures and Programming Spring / 28

Binary Trees, Binary Search Trees

Programming II (CS300)

Trees. CSE 373 Data Structures

Data Structure Lecture#10: Binary Trees (Chapter 5) U Kang Seoul National University

Trees : Part 1. Section 4.1. Theory and Terminology. A Tree? A Tree? Theory and Terminology. Theory and Terminology

Binary Trees

Tree Structures. A hierarchical data structure whose point of entry is the root node

Trees. Trees. CSE 2011 Winter 2007

Chapter 11.!!!!Trees! 2011 Pearson Addison-Wesley. All rights reserved 11 A-1

Chapter 11.!!!!Trees! 2011 Pearson Addison-Wesley. All rights reserved 11 A-1

CSC148 Week 6. Larry Zhang

Trees. Q: Why study trees? A: Many advance ADTs are implemented using tree-based data structures.

Chapter 20: Binary Trees

TREES. Trees - Introduction

Why Do We Need Trees?

References and Homework ABSTRACT DATA TYPES; LISTS & TREES. Abstract Data Type (ADT) 9/24/14. ADT example: Set (bunch of different values)

COSC 2011 Section N. Trees: Terminology and Basic Properties

Trees 11/15/16. Chapter 11. Terminology. Terminology. Terminology. Terminology. Terminology

Data Structures and Algorithms

Principles of Computer Science

BBM 201 Data structures

March 20/2003 Jayakanth Srinivasan,

CE 221 Data Structures and Algorithms

What is a Tree. Trees. Tree ADT ( 6.1.2) Tree Terminology. subtree. In computer science, a tree is an abstract model

Introduction to Binary Trees

Data Structures Lecture 6

Section 5.5. Left subtree The left subtree of a vertex V on a binary tree is the graph formed by the left child L of V, the descendents

INF2220: algorithms and data structures Series 1

Garbage Collection: recycling unused memory

Trees. Dr. Ronaldo Menezes Hugo Serrano Ronaldo Menezes, Florida Tech

Topic 18 Binary Trees "A tree may grow a thousand feet tall, but its leaves will return to its roots." -Chinese Proverb

Advanced Java Concepts Unit 5: Trees. Notes and Exercises

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

Data Structures and Algorithms

About This Lecture. Trees. Outline. Recursive List Definition slide 1. Recursive Tree Definition. Recursive List Definition slide 2

Trees. Introduction & Terminology. February 05, 2018 Cinda Heeren / Geoffrey Tien 1

Trees. Truong Tuan Anh CSE-HCMUT

Trees. Make Money Fast! Stock Fraud. Bank Robbery. Ponzi Scheme. Trees Goodrich, Tamassia

CSE 230 Intermediate Programming in C and C++ Binary Tree

Binary Trees. Height 1

Trees. Estruturas de Dados / Programação 2 Árvores. Márcio Ribeiro twitter.com/marciomribeiro. Introduc)on. Hierarchical structure

CS302 - Data Structures using C++

Definitions A A tree is an abstract t data type. Topic 17. "A tree may grow a. its leaves will return to its roots." Properties of Trees

Terminology. The ADT Binary Tree. The ADT Binary Search Tree

Tree traversals and binary trees

CSE 214 Computer Science II Introduction to Tree

TREES Lecture 10 CS2110 Spring2014

CS24 Week 8 Lecture 1

Abstract Data Structures IB Computer Science. Content developed by Dartford Grammar School Computer Science Department

CS 231 Data Structures and Algorithms Fall Recursion and Binary Trees Lecture 21 October 24, Prof. Zadia Codabux

Name CPTR246 Spring '17 (100 total points) Exam 3

a graph is a data structure made up of nodes in graph theory the links are normally called edges


Chapter 5. Binary Trees

Data Structure - Binary Tree 1 -

Algorithms and Data Structures

CISC 235 Topic 3. General Trees, Binary Trees, Binary Search Trees

CS61B Lecture #20: Trees. Last modified: Wed Oct 12 12:49: CS61B: Lecture #20 1

A set of nodes (or vertices) with a single starting point

Trees Algorhyme by Radia Perlman

Lecture 26. Introduction to Trees. Trees

CSI33 Data Structures

Course Review for. Cpt S 223 Fall Cpt S 223. School of EECS, WSU

BST Implementation. Data Structures. Lecture 4 Binary search trees (BST) Dr. Mahmoud Attia Sakr University of Ain Shams

Binary Tree. Binary tree terminology. Binary tree terminology Definition and Applications of Binary Trees

Lecture Notes 16 - Trees CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson

csci 210: Data Structures Trees

Discussion 2C Notes (Week 8, February 25) TA: Brian Choi Section Webpage:

Trees. Tree Structure Binary Tree Tree Traversals

Tree. Virendra Singh Indian Institute of Science Bangalore Lecture 11. Courtesy: Prof. Sartaj Sahni. Sep 3,2010

Outline. Preliminaries. Binary Trees Binary Search Trees. What is Tree? Implementation of Trees using C++ Tree traversals and applications

Trees Chapter 19, 20. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Binary Trees. Examples:

Transcription:

The tree data structure 1 Trees COL 106 Amit Kumar Shweta Agrawal Acknowledgement :Many slides are courtesy Douglas Harder, UWaterloo 1

Trees The tree data structure 3 A rooted tree data structure stores information in nodes Similar to linked lists: There is a first node, or root Each node has variable number of references to successors (children) Each node, other than the root, has exactly one node as its predecessor (or parent)

The tree data structure 4 What are trees suitable for? 4

The tree data structure To store hierarchy of people 5

The tree data structure To store organization of departments 6 6

The tree data structure To capture the evolution of languages 7 7

The tree data structure To organize file-systems 8 Unix file system

The tree data structure Markup elements in a webpage 9 9

The tree data structure To store phylogenetic data 10 This will be our running example. Will illustrate tree concepts using actual phylogenetic data. 10

Terminology The tree data structure 11 All nodes will have zero or more child nodes or children I has three children: J, K and L For all nodes other than the root node, there is one parent node H is the parent of I

Terminology The tree data structure 12 The degree of a node is defined as the number of its children: deg(i) = 3 Nodes with the same parent are siblings J, K, and L are siblings

Terminology The tree data structure 13 Phylogenetic trees have nodes with degree 2 or 0:

Terminology The tree data structure 14 Nodes with degree zero are also called leaf nodes All other nodes are said to be internal nodes, that is, they are internal to the tree

Terminology The tree data structure 15 Leaf nodes:

Internal nodes: Terminology The tree data structure 16

Terminology The tree data structure 17 These trees are equal if the order of the children is ignored (Unordered trees ) They are different if order is relevant (ordered trees) We will usually examine ordered trees (linear orders) In a hierarchical ordering, order is not relevant

Terminology The tree data structure 18 The shape of a rooted tree gives a natural flow from the root node, or just root

Terminology The tree data structure 19 A path is a sequence of nodes (a 0, a 1,..., a n ) where a k + 1 is a child of a k is The length of this path is n E.g., the path (B, E, G) has length 2

Terminology The tree data structure 20 Paths of length 10 (11 nodes) and 4 (5 nodes) Start of these paths End of these paths

Terminology The tree data structure 21 For each node in a tree, there exists a unique path from the root node to that node The length of this path is the depth of the node, e.g., E has depth 2 L has depth 3

Terminology The tree data structure 22 Nodes of depth up to 17 0 4 9 14 17

Terminology The tree data structure 23 The height of a tree is defined as the maximum depth of any node within the tree The height of a tree with one node is 0 Just the root node For convenience, we define the height of the empty tree to be 1

Terminology The height of this tree is 17 The tree data structure 24 17

Terminology The tree data structure 25 If a path exists from node a to node b: a is an ancestor of b b is a descendent of a Thus, a node is both an ancestor and a descendant of itself We can add the adjective strict to exclude equality: a is a strict descendent of b if a is a descendant of b but a b The root node is an ancestor of all nodes

Terminology The tree data structure 26 The descendants of node B are B, C, D, E, F, and G: The ancestors of node I are I, H, and A:

Terminology The tree data structure 27 All descendants (including itself) of the indicated node

Terminology The tree data structure 28 All ancestors (including itself) of the indicated node

Terminology The tree data structure 29 Another approach to a tree is to define the tree recursively: A degree-0 node is a tree A node with degree n is a tree if it has n children and all of its children are disjoint trees (i.e., with no intersecting nodes) Given any node a within a tree with root r, the collection of a and all of its descendants is said to be a subtree of the tree with root a

The tree data structure Example: XHTML 30 Consider the following XHTML document <html> <head> </head> <title>hello World!</title> <body> <h1>this is a <u>heading</u></h1> <p>this is a paragraph with some <u>underlined</u> text.</p> </body> </html>

The tree data structure Example: XHTML 31 Consider the following XHTML document <html> <head> <title>hello World!</title> </head> <body> <h1>this is a <u>heading</u></h1> body of page </body> </html> <p>this is a paragraph with some <u>underlined</u> text.</p> title heading underlining paragraph

The tree data structure Example: XHTML 32 The nested tags define a tree rooted at the HTML tag <html> <head> </head> <body> <title>hello World!</title> <h1>this is a <u>heading</u></h1> <p>this is a paragraph with some <u>underlined</u> text.</p> </body> </html>

The tree data structure Example: XHTML 33 Web browsers render this tree as a web page

Iterator ADT Most ADTs in Java can provide an iterator object, used to traverse all the data in any linear ADT.

Iterator Interface public interface Iterator<E>{ boolean hasnext(); E next(); void remove(); // Optional }

Getting an Iterator You get an iterator from an ADT by calling the method iterator(); Iterator<Integer> iter = mylist.iterator();

Now a simple while loop can process each data value in the ADT: while(iter.hasnext()) { } process iter.next()

Adding Iterators to SimpleArrayList is easy First, we add the iterator() method to SimpleArrayList: public Iterator<E> iterator(){ } return new ArrayListIterator<E>(this);

Then we implement the iterator class for Lists: import java.util.*; public class ArrayListIterator<E> implements Iterator<E> { // *** fields *** private SimpleArrayList<E> list; private int curpos; public ArrayListIterator( SimpleArrayList<E> list) { this.list = list; curpos = 0; }

public boolean hasnext() { return curpos < list.size(); } public E next() { if (!hasnext()) throw new NoSuchElementException(); } E result = list.get(curpos); curpos++; return result; public void remove() { throw new UnsupportedOperationException(); } }

Position ADT The tree data structure 43 Say vector contains an element Delhi that we want to keep track of The index of the element may keep changing depending on insert/delete operations A position s, may be associated with the element Delhi (say at time of insertion) s lets us access Delhi via s.element() even if the index of Delhi changes in the container, unless we explicitly remove s A position ADT is associated with a particular container. s Delhi 43

Tree ADT The tree data structure 44 We use positions to abstract nodes Generic methods: integer size() boolean isempty() objectiterator elements() positioniterator positions() Accessor methods: position root() position parent(p) positioniterator children(p) Query methods: boolean isinternal(p) boolean isleaf (p) boolean isroot(p) Update methods: swapelements(p, q) object replaceelement(p, o) Additional update methods may be defined by data structures implementing the Tree ADT 44

The tree data structure A Linked Structure for General Trees 45 A node is represented by an object storing Element Parent node Sequence of children nodes Node objects implement the Position ADT B 0 0 0 A D F B A D F 0 0 C E C E 45

The tree data structure Tree using Array 46 Each node contains a field for data and an array of pointers to the children for that node Missing child will have null pointer Tree is represented by pointer to root Allows access to i th child in O(1) time Very wasteful in space when only few nodes in tree have many children (most pointers are null) 46

The tree data structure Tree Traversals 47 A traversal visits the nodes of a tree in a systematic manner We will see three types of traversals Pre-order Post-order In-order 47

The tree data structure Flavors of (Depth First) Traversal 48 In a preorder traversal, a node is visited before its descendants In a postorder traversal, a node is visited after its descendants In an inorder traversal a node is visited after its left subtree and before its right subtree 48

The tree data structure Preorder Traversal 49 Process the root Process the nodes in the all subtrees in their order Algorithm preorder(v) visit(v) for each child w of v preorder(w) Lecture 5: Trees

Preorder Traversal P A S A M L E T R E E Preorder traversal: node is visited before its descendants

The tree data structure Postorder traversal 51 1. Process the nodes in all subtrees in their order 2. Process the root Algorithm postorder(v) for each child w of v postorder(w) visit(v) 51

Postorder Traversal P A S A M L E T R E E Postorder traversal: node is visited before its descendants

The tree data structure Inorder traversal 53 1. Process the nodes in the left subtree 2. Process the root 3. Process the nodes in the right subtree Algorithm InOrder(v) InOrder(v->left) visit(v) InOrder(v->right) For simplicity, we consider tree having at most 2 children, though it can be generalized. 53

Inorder Traversal P A S A M L E T R E Inorder traversal: node is visited after its left subtree and before its right subtree E

The tree data structure Non-Recursive preorder traversal 55 1. Start from root. 2. Print the node. 3. Push right child onto to stack. 4. Push left child onto to stack. 5. Pop node from the stack. 6. Repeat Step 2 to 5 till stack is not empty. 55

Computing Height of Tree Can be computed using the following idea: 1. The height of a leaf node is 0 2. The height of a node other than the leaf is the maximum of the height of the left subtree and the height of the right subtree plus 1. Height(v) = max[height(v left) + height(v right)] + 1 Details left as exercise. 58

The tree data structure 59 Binary Trees Every node has degree up to 2. Proper binary tree: each internal node has degree exactly 2. 59

The tree data structure Binary Tree 60 A binary tree is a tree with the following properties: Each internal node has two children 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 disjoint binary tree Applications: D arithmetic expressions decision processes searching B E A F C G H I 60

The tree data structure Arithmetic Expression Tree 61 Binary tree associated with an arithmetic expression internal nodes: operators leaves: operands Example: arithmetic expression tree for the expression (2 * (a - 1) + (3 * b)) + * * 2-3 b a 1 61

How many leaves L does a proper binary tree of height h have? The number of leaves at depth d = 2 d If the height of the tree is h it has 2 h leaves. L = 2 h. 64

What is the height h of a proper binary tree with L leaves? leaves = 1 height = 0 leaves = 2 height = 1 leaves = 4 height = 2 leaves = L height = Log 2 L Since L = 2 h log 2 L = log 2 2 h h = log 2 L Data Structures and Algorithms 65

The number of internal nodes of a proper binary tree of height h is? Internal nodes = 0 height = 0 Internal nodes = 1 height = 1 Internal nodes = 1 + 2 height = 2 Internal nodes = 1 + 2 + 4 height = 3 1 + 2 + 2 2 +... + 2 h-1 = 2 h -1 Geometric series Thus, a complete binary tree of height = h has 2 h -1 internal nodes. 66

The number of nodes n of a proper binary tree of height h is? nodes = 1 height = 0 nodes = 3 height = 1 nodes = 7 height = 2 nodes = 2 h+1-1 height = h Since L = 2 h and since the number of internal nodes = 2 h -1 the total number of nodes n = 2 h + 2 h -1 = 2(2 h ) 1 = 2 h+1-1. 67

If the number of nodes is n then what is the height? nodes = 1 height = 0 nodes = 3 height = 1 nodes = 7 height = 2 nodes = n height = Log 2 (n+1) - 1 Since n = 2 h+1-1 n + 1 = 2 h+1 Log 2 (n+1) = Log 2 2 h+1 Log 2 (n+1) = h+1 h = Log 2 (n+1) - 1 68

BinaryTree ADT The BinaryTree ADT extends the Tree ADT, i.e., it inherits all the methods of the Tree ADT Additional methods: position leftchild(p) position rightchild(p) position sibling(p) Update methods may be defined by data structures implementing the BinaryTree ADT 69