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

Similar documents
Binary Trees, Binary Search Trees

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

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

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

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

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

Trees, Binary Trees, and Binary Search Trees

Data Structure - Binary Tree 1 -

Binary Trees. Examples:

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

Binary Trees: Practice Problems

Programming II (CS300)

Binary Trees. Height 1

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

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

TREES. Trees - Introduction

Trees. Truong Tuan Anh CSE-HCMUT

Principles of Computer Science

Data Structures in Java

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

Data Structure. Chapter 5 Trees (Part II) Angela Chih-Wei Tang. National Central University Jhongli, Taiwan

BBM 201 Data structures

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

3 Trees: traversal and analysis of standard search trees. Summer Term 2010

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

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

3 Trees: traversal and analysis of standard search trees

Binary Trees and Binary Search Trees

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

Cpt S 122 Data Structures. Data Structures Trees

Algorithms and Data Structures

Binary Trees

Trees. CSE 373 Data Structures

CS350: Data Structures Binary Search Trees

Chapter 20: Binary Trees

Algorithms. AVL Tree

(2,4) Trees. 2/22/2006 (2,4) Trees 1

Module 04 Trees Contents

Binary Search Trees. What is a Binary Search Tree?

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

We have the pointers reference the next node in an inorder traversal; called threads

Complete Binary Trees

Binary Trees. College of Computing & Information Technology King Abdulaziz University. CPCS-204 Data Structures I

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

CS302 - Data Structures using C++

CS102 Binary Search Trees

CS 350 : Data Structures Binary Search Trees

Bioinformatics Programming. EE, NCKU Tien-Hao Chang (Darby Chang)

[ DATA STRUCTURES ] Fig. (1) : A Tree

CHAPTER 5. Trees CHAPTER 5 1/70

Trees, Part 1: Unbalanced Trees

CE 221 Data Structures and Algorithms

tree nonlinear Examples

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

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

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

(2,4) Trees Goodrich, Tamassia (2,4) Trees 1

Introduction to Computers and Programming. Concept Question

Data Structures Question Bank Multiple Choice

CMSC 341. Binary Search Trees CMSC 341 BST

Garbage Collection: recycling unused memory

Module 4: Index Structures Lecture 13: Index structure. The Lecture Contains: Index structure. Binary search tree (BST) B-tree. B+-tree.

Data Structures and Algorithms

Sorted Arrays. Operation Access Search Selection Predecessor Successor Output (print) Insert Delete Extract-Min

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

INF2220: algorithms and data structures Series 1

Chapter 5. Binary Trees

Topic 14. The BinaryTree ADT

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

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

Algorithms in Systems Engineering ISE 172. Lecture 16. Dr. Ted Ralphs

8. Binary Search Tree

Search Trees. Undirected graph Directed graph Tree Binary search tree

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

Lecture 6: Analysis of Algorithms (CS )

Trees. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University

CS 234. Module 5. October 18, CS 234 Module 5 ADTS with items related by structure 1 / 25

Binary search trees. Binary search trees are data structures based on binary trees that support operations on dynamic sets.

Binary Search Trees. See Section 11.1 of the text.

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

Search Trees. Data and File Structures Laboratory. DFS Lab (ISI) Search Trees 1 / 17

Binary search trees 3. Binary search trees. Binary search trees 2. Reading: Cormen et al, Sections 12.1 to 12.3

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

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

Binary search trees (BST) Binary search trees (BST)

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

CMSC 341 Lecture 10 Binary Search Trees

CSI33 Data Structures

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

Why Do We Need Trees?

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

6-TREE. Tree: Directed Tree: A directed tree is an acyclic digraph which has one node called the root node

Analysis of Algorithms

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

March 20/2003 Jayakanth Srinivasan,

TREES Lecture 12 CS2110 Spring 2018

Data Structures and Algorithms for Engineers

Data Structures Lab II. Binary Search Tree implementation

Tree Data Structures CSC 221

CSCI2100B Data Structures Trees

Transcription:

Tree Structures Definitions: o A tree is a connected acyclic graph. o A disconnected acyclic graph is called a forest o A tree is a connected digraph with these properties: There is exactly one node (Root) with in-degree=0 All other nodes have in-degree=1 A leaf is a node with out-degree=0 There is exactly one path from the root to any leaf o The degree of a tree is the maximum out-degree of the nodes in the tree. o If (X,Y) is a path: X is an ancestor of Y, and Y is a descendant of X. Root X Y CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 1

Level of a node: Level 0 or 1 1 or 2 2 or 3 3 or 4 Height or depth: o The depth of a node is the number of edges from the root to the node. o The root node has depth zero o The height of a node is the number of edges from the node to the deepest leaf. o The height of a tree is a height of the root. o The height of the root is the height of the tree o Leaf nodes have height zero o A tree with only a single node (hence both a root and leaf) has depth and height zero. o An empty tree (tree with no nodes) has depth and height 1. o It is the maximum level of any node in the tree. CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 2

o Example: Level 0 or 1 1 or 2 2 or 3 3 or 4 Depth=2 Height=0 Depth=1 Height=2 Depth=2 Height=1 o Please note that if you label the level starting from 1, the depth (height) is level-1 (max level -1) Children, Parents, and Siblings Subtree Properties: (1) for a tree T =(V,E), where n= V and e= E, we have e = n - 1 CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 3

Binary Trees o Definitions: It is a tree whose degree is 2 The two children are called left and right children o Properties: Strictly binary: Each node has either two children or 0 Full Binary tree: A tree is a full binary tree of depth h iff each node of level h is a leaf and each intermediate node has left and right children. Complete Binary tree: Every intermediate node in levels between 0 and h-2 have 2 children Every node in level h-1 has either 2 children or 1 child. If there is one child, then it is a left child. CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 4

Balanced Binary Tree : A tree is a balanced (or height balanced) BT iff for each node X in T, the depth of the left and right subtrees of X differ by at most 1. Lemma 1: o The maximum number of nodes on level i of a binary tree is 2 i (starting from level 0). o The maximum number of nodes in a binary tree of depth k is: 2 k+1-1, k>0 (starting from level 0). Lemma 2: o For any non empty binary tree, T, if n 0 is the number of leaves and n 2 is the number of nodes of degree 2, then o Proof: n 0 = n 2 + 1 The total number of nodes in a BT T is: n = n 0 + n 1 + n 2 n i is the number of nodes of degree i (i children) for i=0, 1, and 2. We have e = n - 1 from property 1 where e is the number of links in T. The number of links e can also be computed as follows: Therefore, n 0 contribute by n 1 contribute by n 2 contribute by 0 links n 1 *1 = n 1 links n 2 *2 = 2n 2 links e = n 1 + 2n 2 = n - 1= n 0 + n 1 + n 2-1 ==> n 0 = n 2 + 1 CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 5

Representations: o Sequential o Linked-list Sequential representation: o For a complete tree of n nodes: (1) The parent of a node i is: i if i Parent( i) No 2 1 parent if i 1( i is the root) (2) The leftchild of a node i is: 2i if 2i n Leftchid( i) Noleftchild if 2i n (3) The rightchild of a node i is: 2i 1 if 2i 1 n Rightchild( i) No Rightchild if 2i 1 n Linked-list representation: CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 6

Binary Tree Traversals There are three traversals: o Inorder: LNR o Preorder: NLR o Postorder: LRN Inorder Traversal: LNR Procedure: Procedure LNR (t:tree); Begin If t=null then return else Begin LNR(t->left); visit(t-data); LNR(t->right); end; Complexity: T(n) = O(n) where n is the number of nodes in T. CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 7

Example: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 LNR: 4-8-2-9-5-10-1-13-11-14-6-3-7-12 NLR: 1-2-4-8-5-9-10-3-6-11-13-14-7-12 LRN: 8-4-9-10-5-2-13-14-11-6-12-7-3-1 CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 8

Binary Search Tree ADT Objective: o Insertion, deletion, and Find take O(log(n)) where n is the number of elements in the list. Definition: o Let us assume that every node in a binary search tree (BST) is assigned a key value X. For every node X in a BST, the keys in the left subtree of the node containing X are smaller than X and the keys in the right subtree of the node containing X are greater than X. x Example: Left subtree of X R 7 Right subtree of X 3 10 1 5 9 11 2 4 6 8 12 CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 9

Operations: o Search or Find o Find_min o Find_max o Insert o Delete Search: function: Node Search(Node T; int x); Begin If ( T == null) then return(null); else Begin If (x < T.data) then return(search(t.left)); else if (x > T.data) then return(search(t.right)); else return(t); End; End; Complexity: O(h) where h is the depth of the tree. CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 10

Insertion in a BST: o There are three steps: create a new node for the element to be inserted Search or Find the location at which the new node will be inserted Insert the new node o Procedure Insert(Node Root; int x) Begin /* The element to be inserted is x */ End; /* Create new node */ t = create_node(); /* Allocate space for x */ t.leftchild = null; t.rightchild = null; t.data = x; /* Search for the insertion location */ p = Root; q = nil; While (p!=null) do Begin End; q = p; if p.data > x then p = p.left; else p = p.right; /* Insert the new element */ If (q == null) /* Empty tree */ then Root = t; else Begin End; if q.data > x then q.left = t; else q.right = t; CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 11

Complexity: O(h) where h is the depth of the tree. Example: CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 12

Deletion in a BST: o There are three cases: Node to be deleted has no children (Leaf). Node to be deleted has one child. Node to be deleted has two children (complicated). o Case 1: Node to be deleted has no children (Leaf): Node to be deleted X R 7 T R 7 3 10 3 10 1 5 9 11 1 5 9 11 2 4 6 8 12 2 4 6 8 Deletion steps: //Delete node with value 12 in a BST with root R //T is the parent of the node that contains 12 T = findparent(r, 12) //Delete the element. T.rightChild = null; CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 13

o Case 2: node to be deleted has one child Y Y X Node to be deleted Z Z Example: R 7 R 7 T 3 10 3 10 1 5 9 11 2 5 9 11 2 4 6 8 4 6 8 Deletion steps: //Delete node with value 1 in a BST with root R //T is the parent of the node that contains 1 T = findparent(r, 1) //Delete the node T = T.rightChild; //Since the left child is null. CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 14

Case 3: node to be deleted has two children X Node to be deleted Left Right Subtree Subtree o X must be replaced by either its: - predecessor ( Max in the left subtree) - successor (Min in the right subtree) R o Example 1: R 7 7 3 T 10 3 T 10 S 2 5 9 11 2 6 9 11 4 6 8 4 6 8 Delete(T.rightChild, T.data); Deletion steps: //Delete node with value 5 in a BST with root R //T is the parent of the node that contains 5 T = findparent(s, 5); S =findsuccessor(t); //Find the min of the right subtree. //Delete the node T.data = S.data; Delete(T.rightChild, T.data); CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 15

o Tree after deleting node 5: R 7 3 10 2 6 9 11 4 8 o Example 2: R 7 3 10 T 3 R 8 10 T 2 5 9 11 2 5 9 11 S 4 6 8 4 6 8 Delete(T.rightChild, T.data); Deletion steps: //Delete node with value 7 in a BST with root R //T is the parent of the node that contains 7 T = findparent(s, 7); S =findsuccessor(t); //Find the min of the right subtree. //Delete the node T.data = S.data; Delete(T.rightChild, T.data); CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 16

o Tree after deleting node 7: R 8 3 10 2 5 9 11 4 6 CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 17

o Procedure Delete(Node Root; int x) Begin If (T ==null) then print ( Sorry the element is not found ); else if (x< T.data) then Delete(T.leftChild,x); /* Go left */ else if (x>t.data) then Delete(T.rightChild,x) /* Go Right */ else Begin If (T.leftChild == null) /* only a right child or none*/ then begin temp = T; T = T.rightChild; free(temp); end; else if (T.rightChild ==null) /* only a left child */ then begin temp = T; T = T.leftChild; end; else begin /* Case 3: Two children. Replace with successor */ temp = Find_min(T.rightChild); T.data = temp.data; Delete(T.rightChild,T.data) end; End; End; CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 18

Time Complexity: o If the tree is a complete binary tree with n nodes, then the worstcase time is O(log n). o If the tree is very unbalanced (i.e. the tree is a linear chain), the worst-case time is O(n). o Luckily, the expected height of a randomly built binary search tree is O(log n) basic operations take time O(log n) on average. CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 19

Threaded Binary Trees Motivations: o To do traversal in languages that do not support recursion o Non- recursive traversals In a binary tree of n nodes there are 2n links out of which n+1 are null links. In case of full tree of depth k, we have n=2 k+1-1. The number of leaves is 2 k = n 1. Therefore, the number of null links is: 2 = n+1. 2* n 1 2 Objective: o Make use of the null links (by A.J. Perlis & C. Thornton). o Replace null links by pointers, called threads, to other nodes in the tree. Threads setup: o If p->right == null then p->right = the node which would be printed after p (inorder o If p->left == null successor of p) when traversing the tree in inorder. then p->left = the node which would be printed before p (inorder predecessor of p) when traversing the tree in inorder. CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 20

o Example: A B C D E F G H I LNR: H D I B E A F C G Implementation: o How to distinguish between threads and normal pointers? Leftthread Leftchild Rightchild Rightthread T Data F Application: o Perform a non-recursive inorder traversal without a stack to simulate recursion. CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 21

Code Example public class BinaryTreeNode { private int key; private BinaryTreeNode leftchild; private BinaryTreeNode rightchild; public BinaryTreeNode(){ key = 0; leftchild = null; rightchild = null; public BinaryTreeNode(int d, BinaryTreeNode left, BinaryTreeNode right){ key = d; leftchild = left; rightchild = right; public int getkey(){ return(key); public BinaryTreeNode getleftchild(){ return(leftchild); public BinaryTreeNode getrightchild(){ return(rightchild); public void setleftchild(binarytreenode node){ leftchild = node; public void setrightchild(binarytreenode node){ rightchild = node; public class BinarySearchTree { private BinaryTreeNode root; public BinarySearchTree(){ this.root = null; public BinaryTreeNode getroot(){ return(root); private void findposition(binarytreenode node, BinaryTreeNode start){ int skey = start.getkey(); if (skey>node.getkey()){ CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 22

if (start.getleftchild() == null){ start.setleftchild(node); else{ findposition(node, start.getleftchild()); else{ if (start.getrightchild() == null){ start.setrightchild(node); else{ findposition(node, start.getrightchild()); public void insertnode(binarytreenode node){ if (root == null){ root = node; else{ findposition(node, this.root); private boolean findelement(binarytreenode node, int x){ if (node == null) return(false); if (x == node.getkey()) return(true); else if (x < node.getkey()) return(findelement(node.getleftchild(), x)); else return(findelement(node.getrightchild(), x)); public int countleaves(binarytreenode node) { if (node == null) return 0; else if (node.getleftchild() == null && node.getrightchild() == null) return 1; else return countleaves(node.getleftchild()) + countleaves(node.getrightchild()); public int computedepth(binarytreenode node){ if (node == null) return 0; CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 23

return (1+ Math.min(computeDepth(node.getLeftChild()), computedepth(node.getrightchild()))); public void inorderprint(binarytreenode node){ public void preorderprint(binarytreenode node){ public int countnodes(binarytreenode node){ public int findmin(binarytreenode node){ public int findmax(binarytreenode node){ o Programming Assignment: Design and implement the missing operations in the Binary Search Tree ADT: - findmin - findmax - countnodes - inorderprint - preorderprint Test your implementation. CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 24