CMSC 341. Introduction to Trees. Textbook sections:

Similar documents
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:

Ordered Lists and Binary Trees

Binary Search Trees (BST)

Data Structures and Algorithms

Binary Trees and Huffman Encoding Binary Search Trees

Algorithms and Data Structures Written Exam Proposed SOLUTION

Full and Complete Binary Trees

Binary Search Trees CMPSC 122

Converting a Number from Decimal to Binary

Data Structure with C

GRAPH THEORY LECTURE 4: TREES

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

Chapter 14 The Binary Search Tree

From Last Time: Remove (Delete) Operation

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

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

Data Structures Fibonacci Heaps, Amortized Analysis

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

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

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

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

Analysis of Algorithms I: Binary Search Trees

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

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

Algorithms and Data Structures

Data Structure [Question Bank]

TREE BASIC TERMINOLOGIES

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

Algorithms Chapter 12 Binary Search Trees

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

Class Notes CS Creating and Using a Huffman Code. Ref: Weiss, page 433

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

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

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

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

Why Use Binary Trees?

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

DATA STRUCTURES USING C

The ADT Binary Search Tree

Binary Heap Algorithms

Data Structures and Algorithms Written Examination

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

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

Parallelization: Binary Tree Traversal

Data Structures. Level 6 C Module Descriptor

Binary Search Trees 3/20/14

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

Binary Trees (1) Outline and Required Reading: Binary Trees ( 6.3) Data Structures for Representing Trees ( 6.4)

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

OPTIMAL BINARY SEARCH TREES

Section IV.1: Recursive Algorithms and Recursion Trees

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

Binary Trees. Wellesley College CS230 Lecture 17 Thursday, April 5 Handout #28. PS4 due 1:30pm Tuesday, April

Analysis of Algorithms I: Optimal Binary Search Trees

Binary Search Trees. basic implementations randomized BSTs deletion in BSTs

Optimal Binary Search Trees Meet Object Oriented Programming

Exam study sheet for CS2711. List of topics

Unordered Linked Lists

10CS35: Data Structures Using C

Union-Find Problem. Using Arrays And Chains

PES Institute of Technology-BSC QUESTION BANK

Classification/Decision Trees (II)

Alex. Adam Agnes Allen Arthur

Lecture Notes on Binary Search Trees

COMPSCI 105 S2 C - Assignment 2 Due date: Friday, 23 rd October 7pm

Algorithms and Data Structures

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

GENERATING THE FIBONACCI CHAIN IN O(log n) SPACE AND O(n) TIME J. Patera

Sample Questions Csci 1112 A. Bellaachia

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

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

The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!

6 March Array Implementation of Binary Trees

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

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

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

2. FINDING A SOLUTION

Chapter 8: Binary Trees

Lecture Notes on Binary Search Trees

- Easy to insert & delete in O(1) time - Don t need to estimate total memory needed. - Hard to search in less than O(n) time

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

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

Binary Coded Web Access Pattern Tree in Education Domain

Object Oriented Software Design

INTERNATIONAL JOURNAL OF PURE AND APPLIED RESEARCH IN ENGINEERING AND TECHNOLOGY

Mathematical Induction. Lecture 10-11

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

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1


The Union-Find Problem Kruskal s algorithm for finding an MST presented us with a problem in data-structure design. As we looked at each edge,

Data Structures and Algorithms(5)

CS 103X: Discrete Structures Homework Assignment 3 Solutions

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

Symbol Tables. Introduction

Data Structures CSC212 (1) Dr Muhammad Hussain Lecture - Binary Search Tree ADT

Lecture 6: Binary Search Trees CSCI Algorithms I. Andrew Rosenberg

Keys and records. Binary Search Trees. Data structures for storing data. Example. Motivation. Binary Search Trees

Big Data and Scripting. Part 4: Memory Hierarchies

Lecture 1: Course overview, circuits, and formulas

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

Transcription:

CMSC 341 Introduction to Trees Textbook sections: 4.1-4.2 1

Tree ADT Tree definition A tree is a set of nodes which may be empty If not empty, then there is a distinguished node r, called root and zero or more non-empty subtrees T 1, T 2, T k, each of whose roots are connected by a directed edge from r. This recursive definition leads to recursive tree algorithms and tree properties being proved by induction. Every node in a tree is the root of a subtree. CMSC 341 Tree Intro 2

A Generic Tree CMSC 341 Tree Intro 3

Tree Terminology Root of a subtree is a child of r. r is the parent. All children of a given node are called siblings. A leaf (or external node) has no children. An internal node is a node with one or more children CMSC 341 Tree Intro 4

More Tree Terminology A path from node V 1 to node V k is a sequence of nodes such that V i is the parent of V i+1 for 1 i k. The length of this path is the number of edges encountered. The length of the path is one less than the number of nodes on the path ( k 1 in this example) The depth of any node in a tree is the length of the path from root to the node. All nodes of the same depth are at the same level. CMSC 341 Tree Intro 5

More Tree Terminology (cont.) The depth of a tree is the depth of its deepest leaf. The height of any node in a tree is the length of the longest path from the node to a leaf. The height of a tree is the height of its root. If there is a path from V 1 to V 2, then V 1 is an ancestor of V 2 and V 2 is a descendent of V 1. CMSC 341 Tree Intro 6

A Unix directory tree CMSC 341 Tree Intro 7

Tree Storage A tree node contains: Data Element Links to other nodes Any tree can be represented with the firstchild, next-sibling implementation. class TreeNode { AnyType element; TreeNode firstchild; TreeNode nextsibling; } CMSC 341 Tree Intro 8

Printing a Child/Sibling Tree // depth equals the number of tabs to indent name private void listall( int depth ) { } printname( depth ); // Print the name of the object if( isdirectory( ) ) public void listall( ) { } listall( 0 ); for each file c in this directory (i.e. for each child) c.listall( depth + 1 ); What is the output when listall( ) is used for the Unix directory tree? CMSC 341 Tree Intro 9

K-ary Tree If we know the maximum number of children each node will have, K, we can use an array of children references in each node. class KTreeNode { } AnyType element; KTreeNode children[ K ]; CMSC 341 Tree Intro 10

Pseudocode for Printing a K-ary Tree // depth equals the number of tabs to indent name private void listall( int depth ) { } printelement( depth ); // Print the object if( children!= null ) for each child c in children array c.listall( depth + 1 ); public void listall( ) { } listall( 0 ); CMSC 341 Tree Intro 11

Binary Trees A special case of K-ary tree is a tree whose nodes have exactly two child references -- binary trees. A binary tree is a rooted tree in which no node can have more than two children AND the children are distinguished as left and right. CMSC 341 Tree Intro 12

The Binary Node Class private class BinaryNode<AnyType> { // Constructors BinaryNode( AnyType theelement ) { this( theelement, null, null ); } BinaryNode( AnyType theelement, BinaryNode<AnyType> lt, BinaryNode<AnyType> rt ) { element = theelement; left = lt; right = rt; } } AnyType element; // The data in the node BinaryNode<AnyType> left; // Left child reference BinaryNode<AnyType> right; // Right child reference CMSC 341 Tree Intro 13

Full Binary Tree A full binary tree is a binary tree in which every node is a leaf or has exactly two children. CMSC 341 Tree Intro 14

FBT Theorem Theorem: A FBT with n internal nodes has n + 1 leaves (external nodes). Proof by induction on the number of internal nodes, n: Base case: Binary Tree of one node (the root) has: zero internal nodes one external node (the root) Inductive Assumption: Assume all FBTs with n internal nodes have n + 1 external nodes. CMSC 341 Tree Intro 15

FBT Proof (cont d) Inductive Step - prove true for a tree with n + 1 internal nodes (i.e. a tree with n + 1 internal nodes has (n + 1) + 1 = n + 2 leaves) Let T be a FBT of n internal nodes. Therefore T has n + 1 leaf nodes. (Inductive Assumption) Enlarge T so it has n+1 internal nodes by adding two nodes to some leaf. These new nodes are therefore leaf nodes. Number of leaf nodes increases by 2, but the former leaf becomes internal. So, # internal nodes becomes n + 1, # leaves becomes (n + 1) + 2-1 = n + 2 CMSC 341 Tree Intro 16

Perfect Binary Tree A Perfect Binary Tree is a Full Binary Tree in which all leaves have the same depth. CMSC 341 Tree Intro 17

PBT Theorem Theorem: The number of nodes in a PBT is 2 h +1-1, where h is height. Proof by strong induction on h, the height of the PBT: Notice that the number of nodes at each level is 2 l. (Proof of this is a simple induction - left to student as exercise). Recall that the height of the root is 0. Base Case: The tree has one node; then h = 0 and n = 1 and 2 (h + 1) - 1 = 2 (0 + 1) 1 = 2 1 1 = 2 1 = 1 = n. Inductive Assumption: Assume true for all PBTs with height h H. CMSC 341 Tree Intro 18

Proof of PBT Theorem(cont) Prove true for PBT with height H+1: Consider a PBT with height H + 1. It consists of a root and two subtrees of height <= H. Since the theorem is true for the subtrees (by the inductive assumption since they have height H) the PBT with height H+1 has (2 (H+1) - 1) nodes for the left subtree + (2 (H+1) - 1) nodesfor the right subtree + 1 node for the root Thus, n = 2 * (2 (H+1) 1) + 1 = 2 ((H+1)+1) - 2 + 1 = 2 ((H+1)+1) - 1 CMSC 341 Tree Intro 19

Complete Binary Tree A Complete Binary Tree is a binary tree in which every level is completely filled, except possibly the bottom level which is filled from left to right. CMSC 341 Tree Intro 20

Tree Traversals Inorder Preorder Postorder Levelorder CMSC 341 Tree Intro 21

Tree Construction Example: Expression tree CMSC 341 Tree Intro 22

Finding an element in a Binary Tree? Return a reference to node containing x, return null if x is not found public BinaryNode<AnyType> find(anytype x) { return find(root, x); } private BinaryNode<AnyType> find( BinaryNode<AnyType> node, AnyType x) { BinaryNode<AnyType> t = null; // in case we don t find it if ( node.element.equals(x) ) // found it here?? return node; // not here, look in the left subtree if(node.left!= null) t = find(node.left,x); // if not in the left subtree, look in the right subtree if ( t == null) t = find(node.right,x); } // return reference, null if not found return t; CMSC 341 Tree Intro 23

Implementation issues CMSC 341 Tree Intro 24

Binary Trees and Recursion A Binary Tree can have many properties Number of leaves Number of interior nodes Is it a full binary tree? Is it a perfect binary tree? Height of the tree Each of these properties can be determined using a recursive function. CMSC 341 Tree Intro 25

Recursive Binary Tree Function return-type function (BinaryNode<AnyType> t) { // base case usually empty tree if (t == null) return xxxx; // determine if the node referred to by t has the property // traverse down the tree by recursively asking left/right // children if their subtree has the property } return theresult; CMSC 341 Tree Intro 26

Is this a full binary tree? boolean isfbt (BinaryNode<AnyType> t) { // base case an empty tee is a FBT if (t == null) return true; } // determine if this node is full // if just one child, return the tree is not full if ((t.left == null && t.right!= null) (t.right == null && t.left!= null)) return false; // if this node is full, ask its subtrees if they are full // if both are FBTs, then the entire tree is an FBT // if either of the subtrees is not FBT, then the tree is not return isfbt( t.right ) && isfbt( t.left ); CMSC 341 Tree Intro 27

Other Recursive Binary Tree Functions Count number of interior nodes int countinteriornodes( BinaryNode<AnyType> t); Determine the height of a binary tree. By convention (and for ease of coding) the height of an empty tree is -1 int height( BinaryNode<AnyType> t); Many others CMSC 341 Tree Intro 28

Other Binary Tree Operations Insertion: inserts a new element into a binary tree? Removal: removes an element from a binary tree? CMSC 341 Tree Intro 29

Tree construction CMSC 341 Tree Intro 30

Constructing Trees Is it possible to reconstruct a Binary Tree from just one of its pre-order, inorder, or postorder sequences? CMSC 341 Tree Intro 31

Constructing Trees (cont) Given two sequences (say pre-order and inorder) is the tree unique? CMSC 341 Tree Intro 32