BST Data Structure A BST node contains: A BST contains

Slides:



Advertisements
Similar presentations
Chapter 12 Binary Search Trees
Advertisements

AVL Trees1 Part-F2 AVL Trees v z. AVL Trees2 AVL Tree Definition (§ 9.2) AVL trees are balanced. An AVL Tree is a binary search tree such that.
Comp 122, Spring 2004 Binary Search Trees. btrees - 2 Comp 122, Spring 2004 Binary Trees  Recursive definition 1.An empty tree is a binary tree 2.A node.
Chapter 4: Trees Part II - AVL Tree
S. Sudarshan Based partly on material from Fawzi Emad & Chau-Wen Tseng
CS 332: Algorithms Binary Search Trees. Review: Dynamic Sets ● Next few lectures will focus on data structures rather than straight algorithms ● In particular,
Search Trees: BSTs and B-Trees David Kauchak cs302 Spring 2013.
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
Binary Search Trees Briana B. Morrison Adapted from Alan Eugenio.
1 Trees. 2 Outline –Tree Structures –Tree Node Level and Path Length –Binary Tree Definition –Binary Tree Nodes –Binary Search Trees.
CSC 213 Lecture 7: Binary, AVL, and Splay Trees. Binary Search Trees (§ 9.1) Binary search tree (BST) is a binary tree storing key- value pairs (entries):
CS 104 Introduction to Computer Science and Graphics Problems Data Structure & Algorithms (4) Data Structures 11/18/2008 Yang Song.
Chapter 12 C Data Structures Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Source: Muangsin / Weiss1 Priority Queue (Heap) A kind of queue Dequeue gets element with the highest priority Priority is based on a comparable value.
David Luebke 1 7/2/2015 ITCS 6114 Binary Search Trees.
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.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures Trees.
CSCE 3110 Data Structures & Algorithm Analysis Binary Search Trees Reading: Chap. 4 (4.3) Weiss.
Compiled by: Dr. Mohammad Alhawarat BST, Priority Queue, Heaps - Heapsort CHAPTER 07.
David Luebke 1 9/18/2015 CS 332: Algorithms Red-Black Trees.
Chapter 19: Binary Trees. Objectives In this chapter, you will: – Learn about binary trees – Explore various binary tree traversal algorithms – Organize.
Chapter 12. Binary Search Trees. Search Trees Data structures that support many dynamic-set operations. Can be used both as a dictionary and as a priority.
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.
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 ),
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.
1 Binary Trees Informal defn: each node has 0, 1, or 2 children Informal defn: each node has 0, 1, or 2 children Formal defn: a binary tree is a structure.
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.
Binary SearchTrees [CLRS] – Chap 12. What is a binary tree ? A binary tree is a linked data structure in which each node is an object that contains following.
Starting at Binary Trees
Search Trees. Binary Search Tree (§10.1) A binary search tree is a binary tree storing keys (or key-element pairs) at its internal nodes and satisfying.
Binary Search Tree Qamar Abbas.
 Trees Data Structures Trees Data Structures  Trees Trees  Binary Search Trees Binary Search Trees  Binary Tree Implementation Binary Tree Implementation.
1 Searching Searching in a sorted linked list takes linear time in the worst and average case. Searching in a sorted array takes logarithmic time in the.
Tree Traversals, TreeSort 20 February Expression Tree Leaves are operands Interior nodes are operators A binary tree to represent (A - B) + C.
1 Chapter 7 Objectives Upon completion you will be able to: Create and implement binary search trees Understand the operation of the binary search tree.
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.
ADT Binary Search Tree Ellen Walker CPSC 201 Data Structures Hiram College.
Red-Black Trees. Review: Binary Search Trees ● Binary Search Trees (BSTs) are an important data structure for dynamic sets ● In addition to satellite.
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.
1. Iterative Preorder Traversal Rpreorder(T) 1. [process the root node] if T!= NULL then Write Data(T) else Write “empty Tree” 2. [process the left subtree]
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.
Trees By JJ Shepherd. Introduction Last time we discussed searching and sorting in a more efficient way Divide and Conquer – Binary Search – Merge Sort.
CS6045: Advanced Algorithms Data Structures. Dynamic Sets Next few lectures will focus on data structures rather than straight algorithms In particular,
BSTs, AVL Trees and Heaps Ezgi Shenqi Bran. What to know about Trees? Height of a tree Length of the longest path from root to a leaf Height of an empty.
Chapter 12 – Data Structures
Search Trees.
Binary Search Tree (BST)
Chapter 10 Search Trees 10.1 Binary Search Trees Search Trees
Binary Search Trees.
Binary Search Tree Chapter 10.
Source: Muangsin / Weiss
Binary Trees, Binary Search Trees
Chapter 20: Binary 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.
Chapter 21: Binary Trees.
CS6045: Advanced Algorithms
Binary Trees, Binary Search Trees
Chapter 20: Binary Trees.
1 Lecture 13 CS2013.
Binary Trees, Binary Search Trees
Data Structures Using C++ 2E
Presentation transcript:

BST Data Structure A BST node contains: A BST contains A key (used to search) The data associated with that key Pointers to children, parent Leaf nodes have NULL pointers for children A BST contains A pointer to the root of the tree.

BST Operations: Insert BST property must be maintained Algorithm sketch: To insert data with key k Compare k to root.key If k < root.key, go left If k > root.key, go right Repeat until you reach a leaf. That's where the new node should be inserted. Note: keep track of prospective parent along the way.

BST Operations: Insert Running time: The new node is inserted at a leaf position, so this depends on the height of the tree. Worst case: Inserting keys 1,2,3,... in this order will result in a tree that looks like a chain: Tree has degenerated to list Height : linear Note also that such a tree is worse than a linked list since it takes up more space (more pointers) 1 2 3

BST Operations: Insert Running time: The new node is inserted at a leaf position, so this depends on the height of the tree. Best case The top levels of the tree are filled up completely The height is then logn where n is the number of nodes in the tree. 12 4 14 2 8 16

BST Operations: Insert The height of a complete (i.e. all levels filled up) BST with n nodes is logarithmic. Why? Level i has 2i nodes, for i=0 (top level) through h (=height) The total number of nodes, n, is then: n = 20+21+...+2h = (2h+1-1)/(2-1) = 2h+1-1 Solving for h gives us h  logn

BST Operations: Insert Analysis conclusion An insert operation consists of two parts: Search for the position best case logarithmic worst case linear Physically insert the node constant

BST Operations: Insert What if we allow duplicate keys? Idea #1 : Always insert in the right subtree Results in very unbalanced tree Idea #2 : Insert in alternate subtrees Makes it difficult to search for all occurrences Idea #3 : All elements with the same key are inserted in a single node Good idea! Easy to search, does not affect balance any more than non-duplicate insertion.

BST Operations: Insert What if we allow variable number of children? (n-ary tree) Idea : Use a vector/list of pointers to children.

BST Operations: Search Take advantage of the BST property. Algorithm sketch: Compare target to root If equal, return success If target < root, search left If target > root, search right Running time: Similar to insert

BST Operations: Delete The Delete operation consists of two parts: Search for the node to be deleted best case constant (deleting the root) worst case linear Delete the node best case? worst case?

BST Operations: Delete CASE #1 The node to be deleted is a leaf node. Easy! Physically remove the node. Constant time We are just resetting its parent's child pointer and deallocating memory

BST Operations: Delete CASE #2 The node to be deleted has exactly one child Easy! Physically remove the node. Constant time We are just resetting its parent's child pointer, its child's parent pointer and deallocating memory

BST Operations: Delete CASE #3 The node to be deleted has two children Not so easy If we physically delete the node, we'll have to place its two children somewhere. This seems to require too much tree restructuring. But we know it's easy to delete a node that has at most one child. What if we find such a node whose contents can be copied over without violating the BST property and then physically delete that node?

BST Operations: Delete CASE #3, continued The node to be deleted, x, has two children Idea: Find the x's immediate successor, y. It is guaranteed to have at most one child Copy the y's contents over to x Physically delete y.

BST Operations: Delete Finding the immediate successor: We know that the node has two children. Due to the BST property, the immediate successor will be in the right subtree. In particular, the immediate successor will be the smallest element in the right subtree. The smallest element in a BST is always the leftmost leaf.

BST Operations: Delete Finding the immediate successor: Since it requires traveling down the tree from the current node to a leaf, it may take up to linear time in the worst case. In the best case it will take logarithmic time. The time to perform the copy and delete the successor is constant.

Binary Search Trees Traversing a tree = visiting its nodes Three major ways to traverse a binary tree: preorder visit root visit left subtree visit right subtree postorder visit left subtree visit right subtree visit root When applied on a BST, it visits the nodes in order from smaller to larger inorder visit left subtree visit root visit right subtree

Binary Search Trees How long does this take? void print_inorder(Node *subroot ) { if (subroot != NULL) { print_inorder(subroot  left); cout << subrootdata; print_inorder(subroot right); } How long does this take? There is exactly one call to print_inorder() for each node of the tree. There are n nodes, so the running time of this operation is (n)

Binary Search Trees A tree may also be traversed one "level" at a time (top to bottom, left to right). This is usually called a level-order traversal. It requires the use of a temporary queue: enqueue root while (queue is not empty) { get the front element, f print f enqueue f's children dequeue }

Binary Search Trees 12 4 14 2 8 16 6 10 in-order : 2 - 4 - 6 - 8 - 10 - 12 - 14 pre-order: 12 - 4 - 2 - 8 - 6 - 10 - 14 - 16 post-order: 2 - 6 - 10 - 8 - 4 - 16 - 14 - 12 level-order: 12 - 4 - 14 - 2 - 8 - 16 - 6 - 10

Binary Search Trees Idea for sorting algorithm: Running time: Given a sequence of integers, insert each one in a BST Perform an inorder traversal. The elements will be accessed in sorted order. Running time: In the worst case, the tree will degenerate to a list. Creation will take quadratic time and traversal will be linear. Total: O(n2) On average, the tree will be mostly balanced. Creation will take O(nlogn) and traversal will again be linear. Total: O(nlogn)

BSTs vs. Lists Time Space In the worst case, all dictionary operations are linear. On average, BSTs are expected to do better. Space BSTs store an additional pointer per node. The BST seemed like a good idea, but in the end it doesn't offer much improvement. We must find a way to keep the tree balanced and guarantee logarithmic height.

Balanced Trees There are several ways to define balance Examples: Force the subtrees of each node to have almost equal heights Place upper and lower bounds on the heights of the subtrees of each node. Force the subtrees of each node to have similar sizes (=number of nodes)