Lecture Objectives  To learn how to use a tree to represent a hierarchical organization of information  To learn how to use recursion to process trees.

Slides:



Advertisements
Similar presentations
TREES Chapter 6. Trees - Introduction  All previous data organizations we've studied are linear—each element can have only one predecessor and successor.
Advertisements

Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
Trees Chapter 8.
Computer Science 2 Data Structures and Algorithms V section 2 Introduction to Trees Professor: Evan Korth New York University.
Fall 2007CS 2251 Trees Chapter 8. Fall 2007CS 2252 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information.
Trees, Binary Trees, and Binary Search Trees COMP171.
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
Trees, Binary Trees, and Binary Search Trees. 2 Trees * Linear access time of linked lists is prohibitive n Does there exist any simple data structure.
Lec 15 April 9 Topics: l binary Trees l expression trees Binary Search Trees (Chapter 5 of text)
Trees CMSC 433 Chapter 8.1 Nelson Padua-Perez Bill Pugh.
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.
Version TCSS 342, Winter 2006 Lecture Notes Trees Binary Trees Binary Search Trees.
CS 146: Data Structures and Algorithms June 18 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
CS 46B: Introduction to Data Structures July 30 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
1 Chapter 18 Trees Objective To learn general trees and recursion binary trees and recursion tree traversal.
Trees Chapter 8. 2 Tree Terminology A tree consists of a collection of elements or nodes, organized hierarchically. The node at the top of a tree is called.
Trees. Tree Terminology Chapter 8: Trees 2 A tree consists of a collection of elements or nodes, with each node linked to its successors The node at the.
Tree. Basic characteristic Top node = root Left and right subtree Node 1 is a parent of node 2,5,6. –Node 2 is a parent of node.
Lecture Objectives  To learn how to use a tree to represent a hierarchical organization of information  To learn how to use recursion to process trees.
Searching: Binary Trees and Hash Tables CHAPTER 12 6/4/15 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,
Lecture 10 Trees –Definiton of trees –Uses of trees –Operations on a tree.
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
CMSC 341 Introduction to Trees. 8/3/2007 UMBC CMSC 341 TreeIntro 2 Tree ADT Tree definition  A tree is a set of nodes which may be empty  If not empty,
DATA STRUCTURES AND ALGORITHMS Lecture Notes 5 Prepared by İnanç TAHRALI.
Binary Trees 2 Overview Trees. Terminology. Traversal of Binary Trees. Expression Trees. Binary Search Trees.
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.
Binary Trees, Binary Search Trees RIZWAN REHMAN CENTRE FOR COMPUTER STUDIES DIBRUGARH UNIVERSITY.
Data Structures and Algorithm Analysis Trees Lecturer: Jing Liu Homepage:
Trees Chapter 8. 2 Tree Terminology A tree consists of a collection of elements or nodes, organized hierarchically. The node at the top of a tree is called.
Trees, Binary Trees, and Binary Search Trees COMP171.
Trees  Linear access time of linked lists is prohibitive Does there exist any simple data structure for which the running time of most operations (search,
Lec 15 Oct 18 Binary Search Trees (Chapter 5 of text)
CE 221 Data Structures and Algorithms Chapter 4: Trees (Binary) Text: Read Weiss, §4.1 – 4.2 1Izmir University of Economics.
IKI 10100I: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100I: Data.
AVL Trees An AVL tree is a binary search tree with a balance condition. AVL is named for its inventors: Adel’son-Vel’skii and Landis AVL tree approximates.
CMSC 341 Introduction to Trees. 2/21/20062 Tree ADT Tree definition –A tree is a set of nodes which may be empty –If not empty, then there is a distinguished.
CISC 235 Topic 3 General Trees, Binary Trees, Binary Search Trees.
Binary Tree. Some Terminologies Short review on binary tree Tree traversals Binary Search Tree (BST)‏ Questions.
1/14/20161 BST Operations Data Structures Ananda Gunawardena.
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.
CMSC 341 Binary Search Trees. 8/3/2007 UMBC CMSC 341 BST 2 Binary Search Tree A Binary Search Tree is a Binary Tree in which, at every node v, the values.
CMSC 202, Version 5/02 1 Trees. CMSC 202, Version 5/02 2 Tree Basics 1.A tree is a set of nodes. 2.A tree may be empty (i.e., contain no nodes). 3.If.
Definitions Read Weiss, 4.1 – 4.2 Implementation Nodes and Links One Arrays Three Arrays Traversals Preorder, Inorder, Postorder K-ary Trees Converting.
BINARY TREES Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary.
1 CSE 326: Data Structures Trees Lecture 6: Friday, Jan 17, 2003.
1 CMSC 341 Introduction to Trees Textbook sections:
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture13.
CC 215 Data Structures Trees
CMSC 341 Introduction to Trees 8/3/2007 CMSC 341 Tree Intro.
Trees.
CSE 373 Data Structures Lecture 7
Binary Trees, Binary Search Trees
CMPE 180A Data Structures and Algorithms in C++ April 26 Class Meeting
8.2 Tree Traversals Chapter 8 - Trees.
Lec 12 March 9, 11 Mid-term # 1 (March 21?)
Trees CSE 373 Data Structures.
Trees.
Data Structures and Algorithm Analysis Trees
Binary Trees, Binary Search Trees
CMSC 341 Introduction to Trees CMSC 341 Tree Intro.
Tree.
Trees.
Trees CSE 373 Data Structures.
CMSC 341 Binary Search Trees 8/3/2007 CMSC 341 BST.
Trees CSE 373 Data Structures.
Binary Trees, Binary Search Trees
8.2 Tree Traversals Chapter 8 - Trees.
Presentation transcript:

Lecture Objectives  To learn how to use a tree to represent a hierarchical organization of information  To learn how to use recursion to process trees  To understand the different ways of traversing a tree  To understand the difference between binary trees, binary search trees, and heaps CS340 1

Tree Terminology and Applications CS340

Trees A tree is a collection of nodes: One node is the root node. A node contains data and has pointers (possibly null) to other nodes, its children. The pointers are directed edges. Each child node can itself be the root of a subtree. A leaf node is a node that has no children. Each node other than the root node has exactly one parent node. 3 Mark Allen Weiss Data Structures and Algorithms in Java (c) 2006 Pearson Education, Inc. All rights reserved

Trees The path from node n 1 to node n k is the sequence of nodes in the tree from n 1 to n k. What is the path from A to Q? From E to P? The length of a path is the number of its edges. What is the length of the path from A to Q? 4 Mark Allen Weiss Data Structures and Algorithms in Java (c) 2006 Pearson Education, Inc. All rights reserved

Trees The depth of a node is the length of the path from the root to that node. What is the depth of node J? Of the root node? The height of a node is the length of the longest path from the node to a leaf node. What is the height of node E? Of the root node? Depth of a tree = depth of its deepest node = height of the tree 5 Mark Allen Weiss Data Structures and Algorithms in Java (c) 2006 Pearson Education, Inc. All rights reserved

Tree Implementation In general, a tree node can have an arbitrary number of child nodes. Therefore, each tree node should have a link to its first child and a link to its next sibling: 6

Tree Implementation Conceptual view of a tree: Implementation view of the same tree: 7 Mark Allen Weiss Data Structures and Algorithms in Java (c) 2006 Pearson Education, Inc. All rights reserved

Tree Traversals There are several different algorithms to “walk” or “traverse” a tree. Each algorithm determines a unique order that each and every node in the tree is “visited”. Preorder traversal: First visit a node. Visit the node before (pre) visiting its child nodes. Then recursively visit each of the node’s child nodes in sibling order. 8

Preorder Tree Traversal 9 private void listAll(int depth) { printName(depth); if (isDirectory()) { for each file f in directory { f.listAll(depth+1); } public void listAll() { listAll(0); } Pseudocode Mark Allen Weiss Data Structures and Algorithms in Java (c) 2006 Pearson Education, Inc. All rights reserved

Postorder Tree Traversal Postorder traversal: First recursively visit each of a node’s child nodes in sibling order. Then visit the node itself. 10

Postorder Tree Traversal 11 private void size() { int totalSize = sizeOfThisFile(); if (isDirectory()) { for each file f in directory { totalSize += f.size() } return totalSize; } Pseudocode Mark Allen Weiss Data Structures and Algorithms in Java (c) 2006 Pearson Education, Inc. All rights reserved

Binary Trees A binary tree is a tree where each node can have 0, 1, or 2 child nodes. The depth of an average binary tree with N nodes is much smaller than N : 12 Mark Allen Weiss Data Structures and Algorithms in Java (c) 2006 Pearson Education, Inc. All rights reserved

Binary Trees An arithmetic expression tree: Understand from the textbook how this tree is built. Or take CS 153: Concepts of Compiler Design 13 Mark Allen Weiss Data Structures and Algorithms in Java (c) 2006 Pearson Education, Inc. All rights reserved

Tree Traversals CS340

Tree Traversals  Walking through the tree in a prescribed order and visiting the nodes as they are encountered  Three common kinds of tree traversal  Inorder  Preorder  Postorder CS340 15

Tree Traversals (cont.) Preorder: visit root node, traverse T L, traverse T R Inorder: traverse T L, visit root node, traverse T R Postorder: traverse T L, traverse T R, visit root node CS340 16

Visualizing Tree Traversals  If we keep following the tree to the left, it will trace a route known as the Euler tour CS340 17

Visualizing Tree Traversals (cont.) A Euler tour (blue path) is a preorder traversal CS340 18

Visualizing Tree Traversals (cont.) If we record a node as we return from traversing its left subtree we get an inorder traversal CS340 19

Visualizing Tree Traversals (cont.) If we record each node as we last encounter it, we get a postorder traversal CS340 20

Traversals of Binary Search Trees and Expression Trees  With inorder traversal nodes are visited in sequence Bob, Helen, Peter, Stacy CS Peter HelenStacy Bob

Traversals of Binary Search Trees and Expression Trees (cont.)  An inorder traversal of an expression tree results in the sequence x + y * a + b / c  Or with parentheses (x + y) * ((a + b)) / c) CS * /+ c+yx ba

Traversals of Binary Search Trees and Expression Trees (cont.) A postorder traversal x y + a b + c / * Postfix form of the expression Operators follow operands CS * /+ c+yx ba

Postorder Tree Traversal Do a postorder walk of our expression tree to output the expression in postfix notation: 24 abc*+de*f+g*+ Mark Allen Weiss Data Structures and Algorithms in Java (c) 2006 Pearson Education, Inc. All rights reserved

Traversals of Binary Search Trees and Expression Trees (cont.) A preorder traversal * + x y / + a b c Prefix form of the expression Operators precede operands CS * /+ c+yx ba

Binary Search Trees A binary search tree has these properties for each of its nodes: All the values in the node’s left subtree is less than the value of the node itself. All the values in the node’s right subtree is greater than the value of the node itself. 26

Binary Search Trees Inorder traversal of a binary tree: Recursively visit a node’s left subtree. Visit the node itself. Recursively visit the node’s right subtree. If you do an inorder walk of a binary search tree, you will visit the nodes in sorted order. 27

Binary Search Trees An inorder walk of the left tree visits the nodes in sorted order: Mark Allen Weiss Data Structures and Algorithms in Java (c) 2006 Pearson Education, Inc. All rights reserved

The Binary Search Tree ADT The node class. This is a nested class of our binary search tree ADT. 29 private static class BinaryNode { AnyType element; // data in the node BinaryNode left; // left child BinaryNode right; // right child BinaryNode(AnyType theElement) { this(theElement, null, null); } BinaryNode(AnyType theElement, BinaryNode lt, BinaryNode rt) { element = theElement; left = lt; right = rt; }

The Binary Search Tree ADT 30 public class BinarySearchTree > { private BinaryNode root; public BinarySearchTree() { root = null; } private BinaryNode findMin(BinaryNode t) {... }... private static class BinaryNode {... } The nested BinaryNode class

The Binary Search Tree: Min and Max Finding the minimum and maximum values in a binary search tree is easy. The leftmost node has the minimum value. The rightmost node has the maximum value. You can find the minimum and maximum values recursively or (better) iteratively. 31

The Binary Search Tree: Min and Max Recursive code to find the minimum value. Chase down the left child links. 32 private BinaryNode findMin(BinaryNode t) { if (t == null) { return null; } else if (t.left == null) { return t; // found the leftmost node } else { return findMin(t.left); }

The Binary Search Tree: Min and Max Iterative code to find the maximum value. Chase down the right child links. 33 private BinaryNode findMax(BinaryNode t) { if (t != null) { while (t.right != null) { t = t.right; } return t; }

The Binary Search Tree: Contains Does a binary search tree contain a target value? Search recursively starting at the root node: If the target value is less than the node’s value, then search the node’s left subtree. If the target value is greater than the node’s value, then search the node’s right subtree. If the values are equal, then yes, the target value is contained in the tree. If you “run off the bottom” of the tree, then no, the target value is not contained in the tree. 34

The Binary Search Tree: Contains 35 private boolean contains(AnyType x, BinaryNode t) { if (t == null) return false; int compareResult = x.compareTo(t.element); if (compareResult < 0) { return contains(x, t.left); } else if (compareResult > 0) { return contains(x, t.right); } else { return true; // Match }

The Binary Search Tree: Insert To insert a target value into the tree: Proceed as if you are checking if the tree contains the target value. As you’re recursively examining left and right subtrees, if you encounter a null link (either a left link or a right link), then that’s where the new value should be inserted. Create a new node containing the target value and replace the null link with a link to the new node. So the new node is attached to the last-visited node. If the target value is already in the tree, either: Insert a duplicate value into the tree. Don’t insert but “update” the existing node. 36

The Binary Search Tree: Insert 37 Mark Allen Weiss Data Structures and Algorithms in Java (c) 2006 Pearson Education, Inc. All rights reserved

The Binary Search Tree: Insert 38 private BinaryNode insert(AnyType x, BinaryNode t) { // Create a new node to be attached // to the last-visited node. if (t == null) { return new BinaryNode<>(x, null, null); } int compareResult = x.compareTo(t.element); // Find the insertion point. if (compareResult < 0) { t.left = insert(x, t.left); } else if (compareResult > 0) { t.right = insert(x, t.right); } else { // Duplicate: do nothing. } return t; } Only when a null link is encountered is a node created and returned. The newly created node will be attached to the last-visited node.

The Binary Search Tree: Remove After removing a node from a binary search tree, the remaining nodes must still be in order. No child case: The target node to be removed is a leaf node. Just remove the target node. 39

The Binary Search Tree: Remove One child case: The target node to be removed has one child node. Change the parent’s link to the target node to point instead to the target node’s child. 40 Mark Allen Weiss Data Structures and Algorithms in Java (c) 2006 Pearson Education, Inc. All rights reserved

The Binary Search Tree: Remove Two children case: The target node to be removed has two child nodes. This is the complicated case. How do we restructure the tree so that the order of the node values is preserved? 41

The Binary Search Tree: Remove Recall what happens you remove a list node. Assume that the list is sorted. If we delete target node 5, which node takes its place? The replacement node is the node that is immediately after the target node in the sorted order. A somewhat convoluted way to do this: Replace the target node’s value with the successor node’s value. Then remove the successor node

The Binary Search Tree: Remove The same convoluted process happens when you remove a node from a binary search tree. The successor node is the node that is immediately after the deleted node in the sorted order. Replace the target node’s value with the successor node’s value. Remove the successor node

The Binary Search Tree: Remove If you remove a target node from a binary search tree, where is the node that is its immediate successor in the sort order? The successor’s value is ≥ than the target value. It must be in the target node’s right subtree. It must be the minimum value in the right subtree. General idea: Replace the value in the target node with the value of the successor node. The successor node is now “empty”. Recursively delete the successor node. 44

The Binary Search Tree: Remove Replace the value of the target node 2 with the value of the successor node 3. Now recursively remove node Mark Allen Weiss Data Structures and Algorithms in Java (c) 2006 Pearson Education, Inc. All rights reserved

The Binary Search Tree: Remove 46 private BinaryNode remove(AnyType x, BinaryNode t) { // If item not found, do nothing. if (t == null) return t; int compareResult = x.compareTo(t.element); if (compareResult < 0) { t.left = remove(x, t.left); } else if (compareResult > 0) { t.right = remove(x, t.right); } // Two children. else if (t.left != null && t.right != null) { t.element = findMin(t.right).element; t.right = remove(t.element, t.right); } // Zero or one child. else { t = (t.left != null) ? t.left : t.right; } return t; } Replace the target value with the successor value. Then recursively remove the successor node.