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

Similar documents
Binary Trees, Binary Search Trees

Chapter 20: Binary Trees

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

Binary Trees

Tree: non-recursive definition. Trees, Binary Search Trees, and Heaps. Tree: recursive definition. Tree: example.

BBM 201 Data structures

Successor/Predecessor Rules in Binary Trees

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

Trees, Binary Trees, and Binary Search Trees

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

Lec 17 April 8. Topics: binary Trees expression trees. (Chapter 5 of text)

Programming II (CS300)

TREES. Trees - Introduction

Binary Trees. Height 1

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

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

Binary Trees and Binary Search Trees

CMSC 341 Lecture 10 Binary Search Trees

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

Tree Data Structures CSC 221

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

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

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

Data and File Structures Laboratory

INF2220: algorithms and data structures Series 1

Why Do We Need Trees?

Binary Search Trees. See Section 11.1 of the text.

Friday Four Square! 4:15PM, Outside Gates

CMSC 341. Binary Search Trees CMSC 341 BST

Unit III - Tree TREES

Announcements. Midterm exam 2, Thursday, May 18. Today s topic: Binary trees (Ch. 8) Next topic: Priority queues and heaps. Break around 11:45am

Advanced Java Concepts Unit 5: Trees. Notes and Exercises

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

March 20/2003 Jayakanth Srinivasan,

CE 221 Data Structures and Algorithms

9/29/2016. Chapter 4 Trees. Introduction. Terminology. Terminology. Terminology. Terminology

COSC 2011 Section N. Trees: Terminology and Basic Properties

Programming II (CS300)

Trees. CSE 373 Data Structures

CSCI2100B Data Structures Trees

Trees. Truong Tuan Anh CSE-HCMUT

Data Structures and Algorithms

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

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

Principles of Computer Science

Trees. Tree Structure Binary Tree Tree Traversals

Introduction. for large input, even access time may be prohibitive we need data structures that exhibit times closer to O(log N) binary search tree

BINARY TREES, THE SEARCH TREE ADT BINARY SEARCH TREES, RED BLACK TREES, TREE TRAVERSALS, B TREES WEEK - 6

Uses for Trees About Trees Binary Trees. Trees. Seth Long. January 31, 2010

Trees CONTENTS. Hours: 8. Marks: 12. Anuradha Bhatia 1

Tree Structures. Definitions: o A tree is a connected acyclic graph. o A disconnected acyclic graph is called a forest

Hierarchical data structures. Announcements. Motivation for trees. Tree overview

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

Binary Trees Fall 2018 Margaret Reid-Miller

Trees: examples (Family trees)

Binary Trees. Examples:

Algorithms. Deleting from Red-Black Trees B-Trees

Binary Trees. BSTs. For example: Jargon: Data Structures & Algorithms. root node. level: internal node. edge.

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

4. Trees. 4.1 Preliminaries. 4.2 Binary trees. 4.3 Binary search trees. 4.4 AVL trees. 4.5 Splay trees. 4.6 B-trees. 4. Trees

CSCI-401 Examlet #5. Name: Class: Date: True/False Indicate whether the sentence or statement is true or false.

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

CSI33 Data Structures

Chapter 5. Binary Trees

Garbage Collection: recycling unused memory

CS302 - Data Structures using C++

Binary Trees and Huffman Encoding Binary Search Trees

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

Data Structures. Trees. By Dr. Mohammad Ali H. Eljinini. M.A. Eljinini, PhD

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

Topic 14. The BinaryTree ADT

CS24 Week 8 Lecture 1

Binary Search Trees Treesort

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

Trees and Tree Traversals. Binary Trees. COMP 210: Object-Oriented Programming Lecture Notes 8. Based on notes by Logan Mayfield

(b) int count = 0; int i = 1; while (i<m) { for (int j=i; j<n; j++) { count = count + 1; i = i + 1; O(M + N 2 ) (c) int count = 0; int i,j,k; for (i=1

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

Binary Search Trees Part Two

If you took your exam home last time, I will still regrade it if you want.

CSC148 Week 6. Larry Zhang

DATA STRUCTURES AND ALGORITHMS. Hierarchical data structures: AVL tree, Bayer tree, Heap

Trees! Ellen Walker! CPSC 201 Data Structures! Hiram College!

- 1 - Handout #22S May 24, 2013 Practice Second Midterm Exam Solutions. CS106B Spring 2013

Also, recursive methods are usually declared private, and require a public non-recursive method to initiate them.

Algorithms and Data Structures

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

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

Binary Tree. Preview. Binary Tree. Binary Tree. Binary Search Tree 10/2/2017. Binary Tree

Trees. Chapter 6. strings. 3 Both position and Enumerator are similar in concept to C++ iterators, although the details are quite different.

Advanced Java Concepts Unit 5: Trees. Notes and Exercises

8. Write an example for expression tree. [A/M 10] (A+B)*((C-D)/(E^F))

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

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

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

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

Tree Travsersals and BST Iterators

Discussion 2C Notes (Week 9, March 4) TA: Brian Choi Section Webpage:

Algorithms and Data Structures (INF1) Lecture 8/15 Hua Lu

Computational Optimization ISE 407. Lecture 16. Dr. Ted Ralphs

Transcription:

Discussion 2C Notes (Week 8, February 25) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs32 Trees Definitions Yet another data structure -- trees. Just like a linked list, a tree consists of nodes (vertices) and links (edges). A tree is a hierarchical structure. That is, a pair of nodes connected by an edge has a parent-child relationship. The following diagram depicts a simple tree of 8 nodes: (" Here, A is the parent of B and C. B and C are the children of A. Because B and C share the parent, they are siblings. We can also say B is an ancestor of F, and G is an descendant of A, and so forth. If you view this structure as a lineage tree, all these terms should be intuitive. In a pointerbased implementation of a tree, a node keeps several pointers that point to the children nodes, and optionally keep a pointer that points to the parent node. The ancestor of all nodes (A in this example) is called the root of the tree. A node with no children is called a leaf (D, E, H, and G). If you look carefully, there is another tree embedded in the tree (formed by the shaded nodes). A tree within another tree is called a subtree. The shaded subtree in the left figure is rooted at B. This subtree rooted at B has 5 nodes. Every node in a tree can serve as the root of some subtree. Therefore, there are a total of 8 subtrees in this tree, rooted at each node. A tree with no node is an empty tree. The height of a tree is defined to be the length the longest path from a root to a leaf. The example tree has the height of 3. A node in a tree generally cannot have an ancestor as its child. This forms a loop in the structure, as depicted on the left side, and therefore, it is no longer a tree. Also, every node except the root must have exactly one parent. A tree is considered malformed when there are nodes that violate these rules. In a general tree, a node can have a variable number of children, as in this tree. For some trees, we limit the number of children a node can have. If you think about it, a tree with each node having only one child is nothing but a linked list. Therefore, a tree can be thought of as a generalization of a linked list. Question: How many edges should there be for a tree of n nodes? Copyright 2011 Brian Choi Week 8, Page 1/8

Binary Tree A binary tree, as evident from its name, is a tree with each node having no more than 2 children. A child of a node is called either the left child or the right child, depending on its location. For example, in the tree in the left figure, D is the left child of B, and E is the right child of E. Question: What is the maximum number of nodes that a height-h binary tree can have? When a tree has this maximum number of nodes given the height, it is called a full binary tree. (" Don t confuse a full binary tree with a complete binary tree. A complete binary tree is almost like a full binary tree in that it is filled up to the second to last level, and all nodes are as far left as possible. An example is shown on right. An implementation of a tree should be very similar to that of a linked list. We first need to define a node, and how they relate to each other. As we did with other data structures, we must also define some operations that go with the structure: 1) inserting a node, 2) removing a node, and 3) searching for a node. For trees, there is another algorithm we need to define: 4) traverse the tree When we say traverse the structure, we mean to iterate over all the elements in a tree. With the structure as awkwardly defined as a tree, there can be several different ways of achieving this goal. Let us examine the options. Tree Traversal Traversing a list is straightforward -- you just keep following the next pointer until you hit the end (or until you come back to the original spot in a circularly linked list). But how about a tree? There is more than one outgoing pointer for each node. Which pointer should you follow first? Before we say anything about the traversals, imagine a structure like the following: struct Node ItemType val; Node *left; Node *right; ; // left child (root of the left subtree) // right child (root of the right subtree) Question: Most algorithms, including traversal algorithms we will discuss, we design for a tree will involve some form of recursion. Why is this so? Copyright 2011 Brian Choi Week 8, Page 2/8

There are mainly three ways of traversing elements in a tree. Preorder We always start at the root node, and when we are at some node, we traverse the subtrees rooted at its children recursively. For simplicity, let us assume the tree is binary. In the preorder traversal, we process the current node first, and recursively process the children trees. For simplicity, assume our process is just cout-ing of the value. It looks as follows: void preorder(node *node) if (node == NULL) // Base case (leaf detection). cout << node->val << " "; // Our "processing" of a node. preorder(node->left); // Visit the left node. preorder(node->right); // Visit the right node. Inorder In the inorder traversal, we start at the root node again, but this time, we explore the left subtree, then print the root node s value, and explore the right subtree as a last step. void inorder(node *node) if (node == NULL) inorder(node->left); cout << node->val << " "; inorder(node->right); Postorder Most of you should see the pattern here. How else can postorder traversal look, but like the following? void postorder(node *node) if (node == NULL) postorder(node->left); postorder(node->right); cout << node->val << " "; Let s try traversing the tree on left. preorder: inorder: postorder: Copyright 2011 Brian Choi Week 8, Page 3/8

Binary Search Tree A binary search tree is a special case of a binary tree, which keeps elements sorted and enhances the performance of a search operation. We will define a set of operations (insertion, etc.) for a binary search tree. Assume the same Node structure defined two pages ago. In a binary search tree, we make sure the following conditions are satisfied at all nodes: 1) If there is a left subtree, all nodes in the left subtree must have values smaller than the current node. 2) If there is a right subtree, all nodes in the right subtree must have values larger than the current node. Generally there is no specific condition for equal values. We will assume all values are unique. An example of a binary search tree is on left. Question: I want to print the values in the increasing order. Which of the above traversal methods shall I use? (" Question: I want to print the values in the decreasing order. Which of the above traversal methods shall I use? (Consider making some modifications to the traversal methods that are defined above.) Insertion Suppose we want to insert a new node into a binary search tree. If the tree is empty (i.e., no node), the new node becomes the only node of the tree and becomes the root. Otherwise, we should trace down the tree to place this new node in the right place. void insert(node* &node, ItemType value) (" )" The above tree is the result of: insert(root, 7); Can you implement the insert function? Make sure to set the values of newnode s parent, left, and right pointers are set correctly at the termination of the function. Hint 1: Why is the pointer being passed in a reference? (You can do it with without &, but this is simpler.) Hint 2: The newly added node will always be a leaf. Question: What is the worst-case time complexity of insertion? Copyright 2011 Brian Choi Week 8, Page 4/8

Search To search a node with a certain value, we can apply one of the traversal functions we defined above. We can apply an approach very similar to binary search we ve seen before. Node *search(const Node *root, ItemType value) Question: What is the worst-case time complexity? Removal Removing a node from a tree might seem a little tricky, but after breaking it down to cases, it might not be that tricky. The simplest case, of course, is when the node to remove is the only node in the tree. You can simply delete the node and set the root pointer to NULL. Another simple case would be when the node is a leaf. You can simply remove the node and set the corresponding pointer to NULL, without worrying about fixing the structure. A more general case would be a node with children. After the removal of a node, this location should be filled in by the node with a value - larger than all nodes in the left subtree - smaller than all nodes in the right subtree If the node has only one child (e.g. 8 in the right figure, with only one child 6), the problem is simplified -- you can take the subtree rooted at the child node and pull the whole subtree one level up. But we cannot do this for a node with two children. There are two subtrees disconnected now, and we cannot pull both trees up. (" )" (" In this case, you must find the node that satisfies the above two conditions. This node is either - the right-most node of the left subtree, or - the left-most node of the right subtree.... and notice how we can easily find this node using the inorder traversal. So we re going to take this new node and insert it to where the node is removed. Wait, what happens to the subtrees of the new node that just got moved? They are disconnected! This suggests that we call the remove function on this new subtree as well. Copyright 2011 Brian Choi Week 8, Page 5/8

void remove(node* &root, ItemType value) if (root == NULL) if (root->val == value) // Case 1: leaf if (root->left == NULL && root->right == NULL) delete root; root = NULL; // Case 2: one child if (root->left!= NULL && root->right == NULL) Node* temp = root; root = root->left; delete temp; if (root->left == NULL && root->right!= NULL) Node* temp = root; root = root->right; delete temp; // Case 3: two children Node* insnode = findnodetoinsert(root->right); // inorder trav. Node* newnode = new Node(insNode->val,root->left, root->right); delete root; remove(insnode); remove(root->left); remove(root->right); Copyright 2011 Brian Choi Week 8, Page 6/8

More Problems on Trees Maximum Value? Assuming ItemType has < and > operators overloaded, define findmax, which returns the maximum value stored in a binary tree rooted at node, where node is never NULL. ItemType findmax(const Node *node) Valid Binary Search Tree? Given a binary tree, how do you check if the binary tree is a valid binary search tree? In other words, are the values organized the right way, such that the following conditions are satisfied? 1) If there is a left subtree, all nodes in the left subtree must have values smaller than the current node. 2) If there is a right subtree, all nodes in the right subtree must have values larger than the current node. Assume the values are unique, and consider you have findmax and findmin (similar to findmax, but returns the minimum value) defined. bool valid(const Node* node) Copyright 2011 Brian Choi Week 8, Page 7/8

Height of the Tree? Given a binary tree, how do you compute the height of the tree? int treeheight(const Node* root) (" )" Possible Multiple Choice Question on the Final(?) Given the binary search tree here, in what order could the nodes possibly have been inserted? Select all possible cases. a) 5, 2, 8, 1, 3, 6, 4, 7 b) 1, 2, 3, 4, 5, 6, 7, 8 c) 8, 7, 6, 5, 4, 3, 2, 1 d) 5, 2, 1, 3, 4, 8, 6, 7 e) 5, 8, 6, 7, 2, 1, 3, 4 Which of the following traversals will the return you the sequence that is one possible order of insertions? a) inorder b) preorder c) postorder Copyright 2011 Brian Choi Week 8, Page 8/8