Binary Trees – Part I CS 367 – Introduction to Data Structures.

Slides:



Advertisements
Similar presentations
CS16: Introduction to Data Structures & Algorithms
Advertisements

S. Sudarshan Based partly on material from Fawzi Emad & Chau-Wen Tseng
Tree Data Structures &Binary Search Tree 1. Trees Data Structures Tree  Nodes  Each node can have 0 or more children  A node can have at most one parent.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Computer Science C++ High School Level By Guillermo Moreno.
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
Binary Search Trees Briana B. Morrison Adapted from Alan Eugenio.
CS 315 March 24 Goals: Heap (Chapter 6) priority queue definition of a heap Algorithms for Insert DeleteMin percolate-down Build-heap.
Binary Trees Terminology A graph G = is a collection of nodes and edges. An edge (v 1,v 2 ) is a pair of vertices that are directly connected. A path,
1 Trees. 2 Outline –Tree Structures –Tree Node Level and Path Length –Binary Tree Definition –Binary Tree Nodes –Binary Search Trees.
Data Structures Data Structures Topic #8. Today’s Agenda Continue Discussing Table Abstractions But, this time, let’s talk about them in terms of new.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Binary Search Trees CSE, POSTECH. Search Trees Search trees are ideal for implementing dictionaries – Similar or better performance than skip lists and.
Binary Search Trees Chapter 6.
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.
1 Joe Meehean.  Important and common problem  Given a collection, determine whether value v is a member  Common variation given a collection of unique.
Week 7 - Wednesday.  What did we talk about last time?  Recursive running time  Master Theorem  Introduction to trees.
Version TCSS 342, Winter 2006 Lecture Notes Trees Binary Trees Binary Search Trees.
Properties: -Each node has a value -The left subtree contains only values less than the parent node’s value -The right subtree contains only values greater.
Recursion and Binary Tree ICS 51 – Introductory Computer Organization.
CSCE 3110 Data Structures & Algorithm Analysis Binary Search Trees Reading: Chap. 4 (4.3) Weiss.
Trees, Binary Search Trees, Recursion, Project 2 Bryce Boe 2013/08/01 CS24, Summer 2013 C.
Recursion Bryce Boe 2013/11/18 CS24, Fall Outline Wednesday Recap Lab 7 Iterative Solution Recursion Binary Tree Traversals Lab 7 Recursive Solution.
BSTImp: Insert, Delete. Inserting an Element into a BST Search for the position in the tree where the element would be found Insert the element in the.
CS 1031 Tree Traversal Techniques; Heaps Tree Traversal Concept Tree Traversal Techniques: Preorder, Inorder, Postorder Full Trees Almost Complete 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,
1 Trees A tree is a data structure used to represent different kinds of data and help solve a number of algorithmic problems Game trees (i.e., chess ),
INTRODUCTION TO BINARY TREES P SORTING  Review of Linear Search: –again, begin with first element and search through list until finding element,
AVL Trees CSCI 2720 Fall 2005 Kraemer. Binary Tree Issue  One major problem with the binary trees we have discussed thus far: they can become extremely.
BINARY SEARCH TREE. Binary Trees A binary tree is a tree in which no node can have more than two children. In this case we can keep direct links to the.
Chapter 6 Binary Trees. 6.1 Trees, Binary Trees, and Binary Search Trees Linked lists usually are more flexible than arrays, but it is difficult to use.
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 Search Trees Binary Search Trees (BST)  the tree from the previous slide is a special kind of binary tree called a binary.
1 Chapter 10 Trees. 2 Definition of Tree A tree is a set of linked nodes, such that there is one and only one path from a unique node (called the root.
2-3 Tree. Slide 2 Outline  Balanced Search Trees 2-3 Trees Trees.
Starting at Binary Trees
1 Trees, Trees, and More Trees. 2 By looking at forests of terms, awesome animations, and complete examples, we hope to get at the root of trees. Hopefully,
 Trees Data Structures Trees Data Structures  Trees Trees  Binary Search Trees Binary Search Trees  Binary Tree Implementation Binary Tree Implementation.
Lec 15 Oct 18 Binary Search Trees (Chapter 5 of text)
Lecture1 introductions and Tree Data Structures 11/12/20151.
Data Structures Trees Phil Tayco Slide version 1.0 Apr. 23, 2015.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for use at Midwestern State University Chapter.
CS 367 – Introduction to Data Structures
Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.
Binary Search Trees (BSTs) 18 February Binary Search Tree (BST) An important special kind of binary tree is the BST Each node stores some information.
1/14/20161 BST Operations Data Structures Ananda Gunawardena.
Binary Search Trees (BST)
COSC 2007 Data Structures II Chapter 13 Advanced Implementation of Tables I.
Trees By JJ Shepherd. Introduction Last time we discussed searching and sorting in a more efficient way Divide and Conquer – Binary Search – Merge Sort.
Linked Lists CS 367 – Introduction to Data Structures.
Unit 7 Trees, Tree Traversals and Binary Search Trees
CSCE 3110 Data Structures & Algorithm Analysis
Recursive Objects (Part 4)
Binary search tree. Removing a node
CISC220 Fall 2009 James Atlas Lecture 13: Binary Trees.
Week 6 - Wednesday CS221.
Binary Search Tree (BST)
Binary Search Trees.
Chapter 20: Binary Trees.
Chapter 21: Binary Trees.
Lec 12 March 9, 11 Mid-term # 1 (March 21?)
CS 367 – Introduction to Data Structures
Find in a linked list? first last 7  4  3  8 NULL
Search Sorted Array: Binary Search Linked List: Linear Search
CSE 373: Data Structures and Algorithms
CSE 373 Data Structures and Algorithms
Search Sorted Array: Binary Search Linked List: Linear Search
Binary Search Trees CS 580U Fall 17.
Presentation transcript:

Binary Trees – Part I CS 367 – Introduction to Data Structures

Trees Nodes –element that contains data Root –node with children and no parent Leaves –node with a parent and no children Arcs –connection between a parent and a child Depth –number of levels in a tree A node can have 1 to n children – no limit Each node can have only one parent

Tree of Depth 4 Root Node Leaf Arc Level 1 Level 2 Level 3 Level 4

Trees vs. Linked Lists Imagine the following linked list How many nodes must be touched to retrieve the number 99? –answer: 7 –must touch every item that appears in the list before the one wanted can be retrieved –random insert, delete, or retrieve is O(n) 76

Trees vs. Linked Lists Now consider the following tree How many nodes must now be touched to retrieve the number 99? –answer: 3 –random insert, delete, or retrieve is O(log n)

Trees vs. Linked Lists Similarities –both can grow to an unlimited size –both require the access of a previous node before the next one Difference –access to a previous node can give access to multiple next nodes if we’re smart (and we will be) we can use this fact to drastically reduce search times

Trees vs. Arrays Consider the following array How many nodes must be touched to retrieve the number 99? –answer: 3 remember the binary search of a sorted array? –searching a sorted array is O(log n) –how about inserting or deleting from an array O(n)

Trees vs. Arrays Similarities –searching the list takes the same time Differences –inserting or deleting from an array (or a vector) is more time consuming –an array is fixed in size vector solves this but introduces other problems

Tree Operations Sorting –way to guarantee the placement of one node with respect to other nodes Searching –finding a node based on a key Inserting –adding a node in a sorted order to the tree Deleting –removing a node from the tree in such a way that the tree is still sorted

Binary Tree One specific type of tree is called a binary tree –each node has at most 2 children right child and left child –sorting the tree is based on the following criteria every item rooted at node N’s right child is greater than N every item rooted at node N’s left child is less than N

Binary Trees

Implementing Binary Trees Each node in the tree must contain a reference to the data, key, right child, and left child class TreeNode { public Object key; public Object data; public TreeNode right; public TreeNode left; public TreeNode(Object k, Object data) { key=k; data=d; } } Tree class only needs reference to root of tree –as well as methods for operating on the tree

Implementing Binary Trees class BinaryTreeRec { private TreeNode root; public BinaryTree() { root = null; } public Object search(Object key) { search(key, root); } private Object search(Object key, TreeNode node); public void insert(Object key, Object data) { insert(key, data, root); } private void insert(Object key, Object data, TreeNode node); public Object delete(Object key) { delete(key, root, null); } private Object delete(Object key, TreeNode cur, TreeNode prev); }

Searching a Binary Tree Set reference P equal to the root node –if P is equal to the key found it –if P is less than key set P equal to the right child node and repeat –if P is greater than key set P equal to the left child node and repeat

Recursive Binary Tree Search private Object search(Object key, TreeNode node) { if(node == null) { return null; } int result = node.key.compareTo(key); if(result == 0) return node.data; // found it else if(result < 0) return search(key, node.right); // key in right subtree else return search(key, node.left); // key in left subtree }

Inserting into Binary Tree Set reference P equal to the root node –if P is equal to null insert the node at position P –if P is less than node to insert set P equal to the right child node and repeat –if P is greater than node to insert set P equal to the left child node and repeat

Recursive Binary Tree Insert private void insert(Object key, Object data, TreeNode node) { if(node == null) { root = new TreeNode(key, data); return; } int result = node.key.compareTo(key); if(result < 0) { if(node.right == null) node.right = new TreeNode(key, data); else insert(key, data, node.right); } else { if(node.left == null) node.left = new TreeNode(key, data); else insert(key, data, node.left); }

Binary Tree Insert One important note from this insert –the key cannot already exists if it does, an error should be returned (our code did not do this) –all keys in a tree must be unique have to have some way to differentiate different nodes

Binary Tree Delete Two possible methods –delete by merging discussed in the book problem is that it can lead to a very unbalanced tree –delete by copying this is the method we will use can still lead to an unbalanced tree, but not nearly as severe

Binary Tree Delete Set reference P equal to the root node –search the tree to find the desired node if it doesn’t exist, return null –once node is found, replace it this is going to require some more explanation

Binary Tree Delete Three possible cases for node to delete –it is a leaf simple, make it’s parent point to null –it has only a single child simple, make it’s parent point to the child –it has two children need to find one of it’s descendants to replace it –we will pick the largest node in the left subtree –could also pick the smallest node in the right subtree this is a fairly complex operation

Simple Cases delete(21)delete(26)

Complex Case delete(76)

Complex Case Notice that we must first find the largest value in the left subtree –keep moving to the next right child until the right.next pointer is equal to null this is the largest node in a subtree –then make this child’s parent point to this child’s left pointer –move this child into the same spot as the deleted node requires the manipulation of a few pointers

Removing a Node public void remove(TreeNode node, TreeNode prev) { TreeNode tmp, p; if(node.right == null) tmp = node.left; else if(node.left == null) tmp = node.right; else { tmp = node.left; p = node; while(tmp.right != null) { p = tmp; tmp = tmp.right; } if(p == node) { p.left = tmp.left; } else { p.right = tmp.left; } tmp.right = node.right; tmp.left = node.left; } if(prev == null) { root = tmp; } else if(prev.left == node) { prev.left = tmp; } else { prev.right = tmp; } }

Recursive Binary Tree Delete private Object delete(Ojbect key, TreeNode cur, TreeNode prev) { if(cur == null) return null; // key not in the tree int result = cur.key.compareTo(key); if(result == 0) { remove(cur, prev); return cur.data; } else if(result < 0) return delete(key, cur.right, cur); else return delete(key, cur.left, cur); }

Iterative Solution Most operations shown so far can easily be converted into an iterative solution class BinaryTreeIter { private TreeNode root; public BinaryTree() { root = null; } public Object search(Object key); public void insert(Object key, Object data); public Object delete(Object key); }

Iterative Binary Search public Object search(Object key) { TreeNode node = root; while(node != null) { int result = node.key.compareTo(key); if(result == 0) return node.data; else if(result < 0) node = node.right; else node = node.left; } return null; }

Iterative Binary Tree Insert public void insert(Object key, Object data) { TreeNode cur = root; TreeNode prev = null; while(cur != null) { if(cur.key.compareTo(key) < 0) { prev = cur; cur = cur.right; } else { prev = cur; cur = cur.left; } } if(prev == null) { root = new TreeNode(key, data); } else if(prev.key.compareTo(key) < 0) prev.right = new TreeNode(key, data); else prev.left = new TreeNode(key, data); }

Iterative Binary Tree Delete public Object delete(Object key) { TreeNode cur = root; TreeNode prev = null; while((cur != null) && (cur.key.compareTo(key) != 0)) { prev = cur; if(cur.key.compareTo(key) < 0) { cur = cur.right; } else { cur = cur.left; } } if(cur != null) { replace(cur, prev); return cur.data; } return null; }