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 ),

Slides:



Advertisements
Similar presentations
Chapter 12 Binary Search Trees
Advertisements

Trees Types and Operations
S. Sudarshan Based partly on material from Fawzi Emad & Chau-Wen Tseng
The complexity and correctness of algorithms (with binary trees as an example)
Binary Trees Chapter 6. Linked Lists Suck By now you realize that the title to this slide is true… By now you realize that the title to this slide is.
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
© 2006 Pearson Addison-Wesley. All rights reserved11 B-1 Chapter 11 (continued) Trees.
Trees, Binary Trees, and Binary Search Trees COMP171.
1 Trees. 2 Outline –Tree Structures –Tree Node Level and Path Length –Binary Tree Definition –Binary Tree Nodes –Binary Search Trees.
Lists A list is a finite, ordered sequence of data items. Two Implementations –Arrays –Linked Lists.
Binary Trees A binary tree is made up of a finite set of nodes that is either empty or consists of a node called the root together with two binary trees,
CS 104 Introduction to Computer Science and Graphics Problems Data Structure & Algorithms (4) Data Structures 11/18/2008 Yang Song.
BST Data Structure A BST node contains: A BST contains
Lec 15 April 9 Topics: l binary Trees l expression trees Binary Search Trees (Chapter 5 of text)
Unit 11a 1 Unit 11: Data Structures & Complexity H We discuss in this unit Graphs and trees Binary search trees Hashing functions Recursive sorting: quicksort,
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Data Structures Using C++ 2E Chapter 11 Binary Trees and B-Trees.
CS21, Tia Newhall Binary Search Trees (BST) 1.Hierarchical data structure with a single pointer to root node 2.Each node has at most two child nodes (a.
More Trees COL 106 Amit Kumar and Shweta Agrawal Most slides courtesy : Douglas Wilhelm Harder, MMath, UWaterloo
Data Structures Using C++1 Chapter 11 Binary Trees.
1 Chapter 18 Trees Objective To learn general trees and recursion binary trees and recursion tree traversal.
Data Structures Arrays both single and multiple dimensions Stacks Queues Trees Linked Lists.
CSCE 3110 Data Structures & Algorithm Analysis Binary Search Trees Reading: Chap. 4 (4.3) Weiss.
Advanced Algorithms Analysis and Design Lecture 8 (Continue Lecture 7…..) Elementry Data Structures By Engr Huma Ayub Vine.
Chapter 19: Binary Trees. Objectives In this chapter, you will: – Learn about binary trees – Explore various binary tree traversal algorithms – Organize.
CS 1031 Tree Traversal Techniques; Heaps Tree Traversal Concept Tree Traversal Techniques: Preorder, Inorder, Postorder Full Trees Almost Complete Trees.
Lecture 10 Trees –Definiton of trees –Uses of trees –Operations on a tree.
S EARCHING AND T REES COMP1927 Computing 15s1 Sedgewick Chapters 5, 12.
© 2011 Pearson Addison-Wesley. All rights reserved 11 B-1 Chapter 11 (continued) Trees.
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,
Binary Trees, Binary Search Trees RIZWAN REHMAN CENTRE FOR COMPUTER STUDIES DIBRUGARH UNIVERSITY.
Trees, Binary Trees, and Binary Search Trees COMP171.
Starting at Binary Trees
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,
 Trees Data Structures Trees Data Structures  Trees Trees  Binary Search Trees Binary Search Trees  Binary Tree Implementation Binary Tree Implementation.
S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 1 Adam Smith L ECTURES Binary Search Trees Algorithms and Data Structures.
Preview  Graph  Tree Binary Tree Binary Search Tree Binary Search Tree Property Binary Search Tree functions  In-order walk  Pre-order walk  Post-order.
Trees : Part 1 Section 4.1 (1) Theory and Terminology (2) Preorder, Postorder and Levelorder Traversals.
+ David Kauchak cs312 Review. + Midterm Will be posted online this afternoon You will have 2 hours to take it watch your time! if you get stuck on a problem,
Binary Search Trees Data Structures Ananda Gunawardena
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.
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
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.
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.
Lecture - 11 on Data Structures. Prepared by, Jesmin Akhter, Lecturer, IIT,JU Threaded Trees Binary trees have a lot of wasted space: the leaf nodes each.
Binary Search Trees (BST)
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.
Trees Ellen Walker CPSC 201 Data Structures Hiram College.
1 Trees General Trees  Nonrecursive definition: a tree consists of a set of nodes and a set of directed edges that connect pairs of nodes.
1 Joe Meehean. A A B B D D I I C C E E X X A A B B D D I I C C E E X X  Terminology each circle is a node pointers are edges topmost node is the root.
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.
BINARY TREES Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary.
1 Trees General Trees  Nonrecursive definition: a tree consists of a set of nodes and a set of directed edges that connect pairs of nodes.
1 Trees : Part 1 Reading: Section 4.1 Theory and Terminology Preorder, Postorder and Levelorder Traversals.
Trees CSIT 402 Data Structures II 1. 2 Why Do We Need Trees? Lists, Stacks, and Queues are linear relationships Information often contains hierarchical.
1 CMSC 341 Introduction to Trees Textbook sections:
1 Trees. 2 Trees Trees. Binary Trees Tree Traversal.
Trees Saurav Karmakar
Binary Search Tree (BST)
Trees.
CMSC 341 Introduction to Trees.
TREE DATA STRUCTURE Data Structure 21-Sep-18 Tree
Binary Trees, Binary Search Trees
Binary Search Trees.
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
Binary Trees, Binary Search Trees
Trees.
Binary Trees, Binary Search Trees
Presentation transcript:

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 ), UNIX directory trees, sorting trees etc We will study extensively two useful kind of trees: Binary Search Trees and Heaps

2 Trees: Definitions Trees have nodes. They also have edges that connect the nodes. Between two nodes there is always only one path. Tree nodes Tree edges

3 Trees: More Definitions Trees are rooted. Once the root is defined (by the user) all nodes have a specific level. Trees have internal nodes and leaves. Every node (except the root) has a parent and it also has zero or more children. level 0 level 1 level 2 level 3 root internal nodes leaves parent and child

4 Binary Trees A binary tree is one that each node has at most 2 children

5 Binary Trees: Definitions Nodes in trees can contain keys (letters, numbers, etc) Complete binary tree: the one where leaves are only in last two bottom levels with bottom one placed as far left as possible

6 Binary Trees: Array Representation Complete Binary Trees can be represented in memory with the use of an array A so that all nodes can be accessed in O(1) time: –Label nodes sequentially top-to-bottom and left-to-right –Left child of A[i] is at position A[2i] –Right child of A[i] is at position A[2i + 1] –Parent of A[i] is at A[i/2]

7 Binary Trees: Array Representation Array A:

8 Binary Trees: Pointer Representation To freely move up and down the tree we need pointers to parent ( NIL for root) and pointers to children ( NIL for leaves) typedef tree_node { int key; struct tree_node *parent; struct tree_node *left, *right; }

9 Tree Traversal: InOrder InOrder is easily described recursively: Visit left subtree (if there is one) In Order Visit root Visit right subtree (if there is one) In Order

10 Another common traversal is PreOrder. It goes as deep as possible (visiting as it goes) then left to right. More precisely (recursively): Visit root Visit left subtree in PreOrder Visit right subtree in PreOrder Tree Traversal: PreOrder

11 PreOrder can also be implemented with a stack, without recursion: Stack S push root onto S repeat until S is empty v = pop S if v is not NULL visit v push v’s right child onto S push v’s left child onto S Tree Traversal: Non-recursive

12 PostOrder traversal also goes as deep as possible, but only visits internal nodes during backtracking. More precisely (recursive): Visit left subtree in PostOrder Visit right subtree in PostOrder Visit root Tree Traversal: PostOrder

13 Tree Traversal: LevelOrder LevelOrder visits nodes level by level from root node: Can be implemented easily with a queue (how??) We will learn this is called Breadth First Search in the data structure called graphs later in 242

14 Binary Search Trees A Binary Search Tree (BST) is a binary tree with the following properties: –The key of a node is always greater than the keys of the nodes in its left subtree –The key of a node is always smaller than the keys of the nodes in its right subtree

15 Binary Search Trees: Examples C AD root

16 Binary Search Trees BST is a tree with the following BST property: key.left < key.parent < key.right NOTE! When nodes of a BST are traversed by Inorder traversal the keys appear in sorted order: inorder(root) { inorder(root.left) print(root.key) inorder(root.right) }

17 Binary Search Trees: Inorder print(8) print(10) print(11) print(14) print(15) print(16) print(18) Inorder visits and prints: Example:

18 Searching for a key in a BST Picture BST’s Parent and Left/Right subtrees as follows: Problem: how do you search BST for node with key x ? L P R

19 Searching for a key in a BST search(root, x) compare x to key of root: - if x = key return - if x search in L - if x > key => search in R search L or R in the exact same way Example: x=8 is ??? X=17 is ???

20 Searching for a key in a BST searchBST(root, key) /* found init to false */ if root=nil return if root.key=key then found=true return root else if key < root.key then searchBST(root.L, key) else searchBST(root.R, key) How can you rewrite searchBST non-recursively?

21 Inserting a new key in a BST How to insert a new key? The same procedure used for search also applies: Determine the location by searching. Search will fail. Insert new key where the search failed. Example: Insert 4?

22 Building a BST Build a BST from a sequence of nodes read one a time Example: Inserting C A B L M (in this order!) 1) Insert C C 2) Insert A C A

23 Building a BST 3) Insert B C A B 4) Insert L 5) Insert M C A B L M C A B L

24 Building a BST Is there a unique BST for letters A B C L M ? NO! Different input sequences result in different trees C A B L M A B C L M Inserting: A B C L M Inserting: C A B L M

25 Sorting with a BST Given a BST can you output its keys in sorted order? Visit keys with Inorder: - visit left - print root - visit right How can you find the minimum? How can you find the maximum? C A B L M Example: A B C L M Inorder visit prints:

26 Deleting from a BST To delete node with key x first you need to search for it. Once found, apply one of the following three cases CASE A: x is a leaf x delete xBST property maintained q r q r p p

27 Deleting from a BST cont. Case B: x is interior with only one subtree L x q r delete x L q r BST property maintained

28 Deleting from a BST cont. Case C: x is interior with two subtrees W x q r delete x Z t s r W q r delete x sZ r BST property maintained t

29 Deleting from a BST cont. Case C cont: … or you can also do it like this W q r Z s r t q < x < r  Q is smaller than the smaller element in Z  R is larger than the largest element in W Can you see other possible ways ?

30 Complexity of Searching with BST What is the complexity of searchBST ? It depends on: –the key x –The other data –The shape of the tree (full, arbitrary) Complexity Analysis: We are interested in best case, worst case and average case

31 Complexity of Searching with BST level 0 level 1 level 2 level 3 height (or depth) of tree = 1 + maximum_level (1+3=4)

32 Complexity of Searching with BST If all nodes in the tree exist then it is called a full BST If all levels are full except for the last level then it is called minimum-level BST

33 Complexity of Searching with BST Theorem: A full BST of height h has nodes Proof:Use induction Inductive Basis: A tree of height 1 has one node (root) Inductive Hypothesis: Assume that a tree of height h has nodes h h

34 Complexity of Searching with BST Inductive step: Connect two trees of height h to make one of height h+1. You need to add one more node for the new root root LR h h+1 By inductive hypothesis the new number of nodes is (2 - 1) + (2 -1) + 1 = ……proved! hhh+1

35 Complexity of Searching with BST Theorem: For a minimum level tree of height h: < # of nodes < hh - 1 Corollary: The tree with the smallest height with n # of nodes it has a height of h = 1 + log n n 2 WHY?

36 Therefore, for a full BST with N nodes the following holds for searchBST: best time analysis ………… O(1) worst time analysis ………… O(log N) average case analysis ………… ??? We need to find what the average is!! Complexity of Searching with BST

37 To define what average means you need to: –Find out all possibilities and … –Determine the probability of each possibility … – that is, you need to find the expected value: Complexity of Searching with BST Possible values for the number of steps j are 1, 2, …, h as we assume that key search value is equally to occur