Bsts ‣ Iteration Algorithms ‣ Ordered Operations FOURTH EDITION ‣ Deletion (See Book Or Videos)

Total Page:16

File Type:pdf, Size:1020Kb

Bsts ‣ Iteration Algorithms ‣ Ordered Operations FOURTH EDITION ‣ Deletion (See Book Or Videos) Algorithms ROBERT SEDGEWICK | KEVIN WAYNE 3.2 BINARY SEARCH TREES ‣ BSTs ‣ iteration Algorithms ‣ ordered operations FOURTH EDITION ‣ deletion (see book or videos) ROBERT SEDGEWICK | KEVIN WAYNE https://algs4.cs.princeton.edu Last updated on 3/1/19 3:45 PM 3.2 BINARY SEARCH TREES ‣ BSTs ‣ iteration Algorithms ‣ ordered operations ‣ deletion (see book or videos) ROBERT SEDGEWICK | KEVIN WAYNE https://algs4.cs.princeton.edu Binary search trees Definition. A BST is a binary tree in symmetric order. root a left link a subtree A binary tree is either: Empty. ・ right child ・Two disjoint binary trees (left and right). of root null links Anatomy of a binary tree parent of A and R Symmetric order. Each node has a key, key left link S and every node’s key is: of E E X Larger than all keys in its left subtree. A R 9 value ・ C H associated ・Smaller than all keys in its right subtree. with R keys smaller than E keys larger than E Anatomy of a binary search tree 3 Differences between heaps and binary search trees Heap BST Supported insert, search, delete, Insert, delete-max operations ordered operations What is inserted Keys Key-value pairs Underlying Resizing array Linked nodes data structure Fixed shape given n Varies; Tree shape (complete binary tree) depends on data Somewhat ordered Totally ordered Ordering of keys parent > child for max heap left child < parent < right child Duplicate keys Yes No allowed? 4 Binary search trees: quiz 1 Which of the following properties hold? A. If a binary tree is heap ordered, then it is symmetrically ordered. B. If a binary tree is symmetrically ordered, then it is heap ordered. C. Both A and B. D. Neither A nor B. max key X X min key H H max key E E S S C C S S A C A R C HR H A E A R E XR X symmetricsymmetric order order heapheap order orderheap order symmetric order 5 BST representation in Java A BST contains a reference to a root Node. A Node is composed of four fields: ・A Key and a Value. ・A reference to the left and right subtree. smaller keys larger keys private class Node { private Key key; BST private Value val; private Node left, right; Node key val public Node(Key key, Value val) { left right this.key = key; this.val = val; } BST with smaller keys BST with larger keys } Binary search tree Key and Value are generic types; Key is Comparable 6 BST implementation (skeleton) public class BST<Key extends Comparable<Key>, Value> { private Node root; root of BST private class Node { /* see previous slide */ } public void put(Key key, Value val) { /* see next slide */ } public Value get(Key key) { /* see next slide */ } public Iterable<Key> keys() { /* see slides in next section */ } public void delete(Key key) { /* see textbook */ } } 7 BST search (get) If less, go left; if greater, go right; if equal, search hit; if null node, search miss. H: search hit S E X A R G: search miss S C H E X M A R C H M 8 BST search: Java implementation Get. Return value corresponding to given key, or null if no such key. public Value get(Key key) { Node x = root; while (x != null) { int cmp = key.compareTo(x.key); if (cmp < 0) x = x.left; else if (cmp > 0) x = x.right; else if (cmp == 0) return x.val; } return null; } Cost. Number of compares = 1 + depth of node. 9 BST insert (put) Associate value with key. inserting L S E X A R C H Search for key, then two cases: M Key in tree ⇒ reset value. search for L ends P ・ at this null link Key not in tree ⇒ add new node. S ・ E X A R C H M create new node L P S E X A R C H M reset links L P on the way up Insertion into a BST 10 BST insert: Java implementation Put. Associate value with key. inserting L Tr i c k y ! S E X A R public void put(Key key, Value val) C H { root = put(root, key, val); } M P private Node put(Node x, Key key, Value val) search for L ends at this null link { S if (x == null) return new Node(key, val); E X int cmp = key.compareTo(x.key); A R if (cmp < 0) x.left = put(x.left, key, val); C H else if (cmp > 0) x.right = put(x.right, key, val); M else if (cmp == 0) x.val = val; create new node L P return x; S } E X A R C H M reset links L P on the way up Cost. Number of compares = 1 + depth of node. Insertion into a BST 11 best case H C S Tree shape A E R X Many BSTs correspond to same set of keys. ・ typical case S Number of compares for bestsearch/insert case = 1 + depth of node. ・ H E X C S A R A E R X C H best case typical case A worst case H S C C S E X E A E R X A R H C H R S X typical case S A worst case E X C BST possibilities A R E C H H R S X BottomA line. worstTree case shape depends on order of insertion. C E BST possibilities H 12 R S X BST possibilities BST insertion: random order visualization Ex. Insert keys in random order. 13 Binary search trees: quiz 2 Suppose that you insert n keys in random order into a BST. What is the expected height of the resulting BST? P H T A. ~ lg n D O S U B. ~ ln n height A E I Y C. ~ 2 lg n D. ~ 2 ln n C M E. ~ 4.31107 ln n L 14 Correspondence between BSTs and quicksort partitioning P H T D O S U A E I Y C M L Remark. Correspondence is 1–1 if array has no duplicate keys. 15 BSTs: mathematical analysis Proposition. If n distinct keys are inserted into a BST in random order, the expected number of compares for a search/insert is ~ 2 ln n. Pf. 1–1 correspondence with quicksort partitioning. Proposition. [Reed, 2003] If n distinct keys are inserted into a BST in random order, the expected height is ~ 4.31107 ln n. How Tall is a Tree? expected depth of How Tall is a Tree? function-call stack in quicksort Bruce Reed Bruce Reed CNRS, Paris, France CNRS, Paris, France [email protected] [email protected] ABSTRACT purpose of this note to prove that for /3 -- ½ + ~,3 we ABSTRACT Let H~ be the height of a randompurpose binary of search this note tree toon prove n thathave: for /3 -- ½ + ~,3 we Let H~ be the height of a randomnodes. binary We search show thattree onthere n existshave: constants a = 4.31107... THEOREM 1. E(H~) = ~logn -/31oglogn + O(1) nodes. We show that there existsand/3 constants = 1.95... a = 4.31107... such that E(H~) = c~logn -/31oglogn + and Var(Hn) = O(1) . and/3 = 1.95... such that E(H~)O(1), = c~logn We also -/31oglogn show that +Var(H~) =THEOREM O(1). 1. E(H~) = ~logn -/31oglogn + O(1) and O(1), We also show that Var(H~) = O(1). Var(Hn) = O(1) . Remark By the definition of a, /3 = 3~ Categories and Subject Descriptors 7"g~" The first defi- Remark By the definition of a, nition/3 = 7"g~"given3~ Theis more first suggestive defi- of why this value is correct, Categories and Subject Descriptors as we will see. But… Worst-case height is n – 1. E.2 [Data Structures]: Trees nition given is more suggestive of why this value is correct, E.2 [Data Structures]: Trees as we will see. For more information on random binary search trees, one 1. THE RESULTS For more information on randommay binary consult search [6],[7], trees, [1], one [2], [9], [4], and [8]. may consult [6],[7], [1], [2], [9], [4],Remark and [8]. After I announced these results, Drmota(unpublished) Unlike quicksort, worst case matters —1. clientTHE RESULTS may notA binary insertsearch tree is a inbinary random tree to each node oforder. which developed an alternative proof of the fact that Var(Hn) = we have associated a key; these Remarkkeys axe drawnAfter I fromannounced some these results, Drmota(unpublished) A binary search tree is a binary tree to each node of which developed an alternative proof ofO(1) the factusing that completely Var(Hn) different= techniques. As our two totally ordered set and the key at v cannot be larger than proofs illuminate different aspects of the problem, we have we have associated a key; these keys axe drawn from some O(1) using completely different techniques. 16 As our two totally ordered set and the key atthe v keycannot at its be right larger child than nor smaller than the key at its left decided to submit the journal versions to the same journal child. Given a binary search treeproofs T and illuminate a new key different k, we aspects of the problem, we have the key at its right child nor smaller than the key at its left decided to submit the journal versionsand asked to the that same they journal be published side by side. child. Given a binary search treeinsert T and k intoa new T bykey traversing k, we the tree starting at the root and inserting k into the first emptyand asked position that at they which be publishedwe side by side.
Recommended publications
  • Trees • Binary Trees • Newer Types of Tree Structures • M-Ary Trees
    Data Organization and Processing Hierarchical Indexing (NDBI007) David Hoksza http://siret.ms.mff.cuni.cz/hoksza 1 Outline • Background • prefix tree • graphs • … • search trees • binary trees • Newer types of tree structures • m-ary trees • Typical tree type structures • B-tree • B+-tree • B*-tree 2 Motivation • Similarly as in hashing, the motivation is to find record(s) given a query key using only a few operations • unlike hashing, trees allow to retrieve set of records with keys from given range • Tree structures use “clustering” to efficiently filter out non relevant records from the data set • Tree-based indexes practically implement the index file data organization • for each search key, an indexing structure can be maintained 3 Drawbacks of Index(-Sequential) Organization • Static nature • when inserting a record at the beginning of the file, the whole index needs to be rebuilt • an overflow handling policy can be applied → the performance degrades as the file grows • reorganization can take a lot of time, especially for large tables • not possible for online transactional processing (OLTP) scenarios (as opposed to OLAP – online analytical processing) where many insertions/deletions occur 4 Tree Indexes • Most common dynamic indexing structure for external memory • When inserting/deleting into/from the primary file, the indexing structure(s) residing in the secondary file is modified to accommodate the new key • The modification of a tree is implemented by splitting/merging nodes • Used not only in databases • NTFS directory structure
    [Show full text]
  • Balanced Trees Part One
    Balanced Trees Part One Balanced Trees ● Balanced search trees are among the most useful and versatile data structures. ● Many programming languages ship with a balanced tree library. ● C++: std::map / std::set ● Java: TreeMap / TreeSet ● Many advanced data structures are layered on top of balanced trees. ● We’ll see several later in the quarter! Where We're Going ● B-Trees (Today) ● A simple type of balanced tree developed for block storage. ● Red/Black Trees (Today/Thursday) ● The canonical balanced binary search tree. ● Augmented Search Trees (Thursday) ● Adding extra information to balanced trees to supercharge the data structure. Outline for Today ● BST Review ● Refresher on basic BST concepts and runtimes. ● Overview of Red/Black Trees ● What we're building toward. ● B-Trees and 2-3-4 Trees ● Simple balanced trees, in depth. ● Intuiting Red/Black Trees ● A much better feel for red/black trees. A Quick BST Review Binary Search Trees ● A binary search tree is a binary tree with 9 the following properties: 5 13 ● Each node in the BST stores a key, and 1 6 10 14 optionally, some auxiliary information. 3 7 11 15 ● The key of every node in a BST is strictly greater than all keys 2 4 8 12 to its left and strictly smaller than all keys to its right. Binary Search Trees ● The height of a binary search tree is the 9 length of the longest path from the root to a 5 13 leaf, measured in the number of edges. 1 6 10 14 ● A tree with one node has height 0.
    [Show full text]
  • Game Trees, Quad Trees and Heaps
    CS 61B Game Trees, Quad Trees and Heaps Fall 2014 1 Heaps of fun R (a) Assume that we have a binary min-heap (smallest value on top) data structue called Heap that stores integers and has properly implemented insert and removeMin methods. Draw the heap and its corresponding array representation after each of the operations below: Heap h = new Heap(5); //Creates a min-heap with 5 as the root 5 5 h.insert(7); 5,7 5 / 7 h.insert(3); 3,7,5 3 /\ 7 5 h.insert(1); 1,3,5,7 1 /\ 3 5 / 7 h.insert(2); 1,2,5,7,3 1 /\ 2 5 /\ 7 3 h.removeMin(); 2,3,5,7 2 /\ 3 5 / 7 CS 61B, Fall 2014, Game Trees, Quad Trees and Heaps 1 h.removeMin(); 3,7,5 3 /\ 7 5 (b) Consider an array based min-heap with N elements. What is the worst case running time of each of the following operations if we ignore resizing? What is the worst case running time if we take into account resizing? What are the advantages of using an array based heap vs. using a BST-based heap? Insert O(log N) Find Min O(1) Remove Min O(log N) Accounting for resizing: Insert O(N) Find Min O(1) Remove Min O(N) Using a BST is not space-efficient. (c) Your friend Alyssa P. Hacker challenges you to quickly implement a max-heap data structure - "Hah! I’ll just use my min-heap implementation as a template", you think to yourself.
    [Show full text]
  • CSE 326: Data Structures Binary Search Trees
    Announcements (1/23/09) CSE 326: Data Structures • HW #2 due now • HW #3 out today, due at beginning of class next Binary Search Trees Friday. • Project 2A due next Wed. night. Steve Seitz Winter 2009 • Read Chapter 4 1 2 ADTs Seen So Far The Dictionary ADT • seitz •Data: Steve • Stack •Priority Queue Seitz –a set of insert(seitz, ….) CSE 592 –Push –Insert (key, value) pairs –Pop – DeleteMin •ericm6 Eric • Operations: McCambridge – Insert (key, value) CSE 218 •Queue find(ericm6) – Find (key) • ericm6 • soyoung – Enqueue Then there is decreaseKey… Eric, McCambridge,… – Remove (key) Soyoung Shin – Dequeue CSE 002 •… The Dictionary ADT is also 3 called the “Map ADT” 4 A Modest Few Uses Implementations insert find delete •Sets • Unsorted Linked-list • Dictionaries • Networks : Router tables • Operating systems : Page tables • Unsorted array • Compilers : Symbol tables • Sorted array Probably the most widely used ADT! 5 6 Binary Trees Binary Tree: Representation • Binary tree is A – a root left right – left subtree (maybe empty) A pointerpointer A – right subtree (maybe empty) B C B C B C • Representation: left right left right pointerpointer pointerpointer D E F D E F Data left right G H D E F pointer pointer left right left right left right pointerpointer pointerpointer pointerpointer I J 7 8 Tree Traversals Inorder Traversal void traverse(BNode t){ A traversal is an order for if (t != NULL) visiting all the nodes of a tree + traverse (t.left); process t.element; Three types: * 5 traverse (t.right); • Pre-order: Root, left subtree, right subtree 2 4 } • In-order: Left subtree, root, right subtree } (an expression tree) • Post-order: Left subtree, right subtree, root 9 10 Binary Tree: Special Cases Binary Tree: Some Numbers… Recall: height of a tree = longest path from root to leaf.
    [Show full text]
  • Heaps a Heap Is a Complete Binary Tree. a Max-Heap Is A
    Heaps Heaps 1 A heap is a complete binary tree. A max-heap is a complete binary tree in which the value in each internal node is greater than or equal to the values in the children of that node. A min-heap is defined similarly. 97 Mapping the elements of 93 84 a heap into an array is trivial: if a node is stored at 90 79 83 81 index k, then its left child is stored at index 42 55 73 21 83 2k+1 and its right child at index 2k+2 01234567891011 97 93 84 90 79 83 81 42 55 73 21 83 CS@VT Data Structures & Algorithms ©2000-2009 McQuain Building a Heap Heaps 2 The fact that a heap is a complete binary tree allows it to be efficiently represented using a simple array. Given an array of N values, a heap containing those values can be built, in situ, by simply “sifting” each internal node down to its proper location: - start with the last 73 73 internal node * - swap the current 74 81 74 * 93 internal node with its larger child, if 79 90 93 79 90 81 necessary - then follow the swapped node down 73 * 93 - continue until all * internal nodes are 90 93 90 73 done 79 74 81 79 74 81 CS@VT Data Structures & Algorithms ©2000-2009 McQuain Heap Class Interface Heaps 3 We will consider a somewhat minimal maxheap class: public class BinaryHeap<T extends Comparable<? super T>> { private static final int DEFCAP = 10; // default array size private int size; // # elems in array private T [] elems; // array of elems public BinaryHeap() { .
    [Show full text]
  • Assignment 3: Kdtree ______Due June 4, 11:59 PM
    CS106L Handout #04 Spring 2014 May 15, 2014 Assignment 3: KDTree _________________________________________________________________________________________________________ Due June 4, 11:59 PM Over the past seven weeks, we've explored a wide array of STL container classes. You've seen the linear vector and deque, along with the associative map and set. One property common to all these containers is that they are exact. An element is either in a set or it isn't. A value either ap- pears at a particular position in a vector or it does not. For most applications, this is exactly what we want. However, in some cases we may be interested not in the question “is X in this container,” but rather “what value in the container is X most similar to?” Queries of this sort often arise in data mining, machine learning, and computational geometry. In this assignment, you will implement a special data structure called a kd-tree (short for “k-dimensional tree”) that efficiently supports this operation. At a high level, a kd-tree is a generalization of a binary search tree that stores points in k-dimen- sional space. That is, you could use a kd-tree to store a collection of points in the Cartesian plane, in three-dimensional space, etc. You could also use a kd-tree to store biometric data, for example, by representing the data as an ordered tuple, perhaps (height, weight, blood pressure, cholesterol). However, a kd-tree cannot be used to store collections of other data types, such as strings. Also note that while it's possible to build a kd-tree to hold data of any dimension, all of the data stored in a kd-tree must have the same dimension.
    [Show full text]
  • L11: Quadtrees CSE373, Winter 2020
    L11: Quadtrees CSE373, Winter 2020 Quadtrees CSE 373 Winter 2020 Instructor: Hannah C. Tang Teaching Assistants: Aaron Johnston Ethan Knutson Nathan Lipiarski Amanda Park Farrell Fileas Sam Long Anish Velagapudi Howard Xiao Yifan Bai Brian Chan Jade Watkins Yuma Tou Elena Spasova Lea Quan L11: Quadtrees CSE373, Winter 2020 Announcements ❖ Homework 4: Heap is released and due Wednesday ▪ Hint: you will need an additional data structure to improve the runtime for changePriority(). It does not affect the correctness of your PQ at all. Please use a built-in Java collection instead of implementing your own. ▪ Hint: If you implemented a unittest that tested the exact thing the autograder described, you could run the autograder’s test in the debugger (and also not have to use your tokens). ❖ Please look at posted QuickCheck; we had a few corrections! 2 L11: Quadtrees CSE373, Winter 2020 Lecture Outline ❖ Heaps, cont.: Floyd’s buildHeap ❖ Review: Set/Map data structures and logarithmic runtimes ❖ Multi-dimensional Data ❖ Uniform and Recursive Partitioning ❖ Quadtrees 3 L11: Quadtrees CSE373, Winter 2020 Other Priority Queue Operations ❖ The two “primary” PQ operations are: ▪ removeMax() ▪ add() ❖ However, because PQs are used in so many algorithms there are three common-but-nonstandard operations: ▪ merge(): merge two PQs into a single PQ ▪ buildHeap(): reorder the elements of an array so that its contents can be interpreted as a valid binary heap ▪ changePriority(): change the priority of an item already in the heap 4 L11: Quadtrees CSE373,
    [Show full text]
  • Splay Trees Last Changed: January 28, 2017
    15-451/651: Design & Analysis of Algorithms January 26, 2017 Lecture #4: Splay Trees last changed: January 28, 2017 In today's lecture, we will discuss: • binary search trees in general • definition of splay trees • analysis of splay trees The analysis of splay trees uses the potential function approach we discussed in the previous lecture. It seems to be required. 1 Binary Search Trees These lecture notes assume that you have seen binary search trees (BSTs) before. They do not contain much expository or backtround material on the basics of BSTs. Binary search trees is a class of data structures where: 1. Each node stores a piece of data 2. Each node has two pointers to two other binary search trees 3. The overall structure of the pointers is a tree (there's a root, it's acyclic, and every node is reachable from the root.) Binary search trees are a way to store and update a set of items, where there is an ordering on the items. I know this is rather vague. But there is not a precise way to define the gamut of applications of search trees. In general, there are two classes of applications. Those where each item has a key value from a totally ordered universe, and those where the tree is used as an efficient way to represent an ordered list of items. Some applications of binary search trees: • Storing a set of names, and being able to lookup based on a prefix of the name. (Used in internet routers.) • Storing a path in a graph, and being able to reverse any subsection of the path in O(log n) time.
    [Show full text]
  • Binary Search Tree
    ADT Binary Search Tree! Ellen Walker! CPSC 201 Data Structures! Hiram College! Binary Search Tree! •" Value-based storage of information! –" Data is stored in order! –" Data can be retrieved by value efficiently! •" Is a binary tree! –" Everything in left subtree is < root! –" Everything in right subtree is >root! –" Both left and right subtrees are also BST#s! Operations on BST! •" Some can be inherited from binary tree! –" Constructor (for empty tree)! –" Inorder, Preorder, and Postorder traversal! •" Some must be defined ! –" Insert item! –" Delete item! –" Retrieve item! The Node<E> Class! •" Just as for a linked list, a node consists of a data part and links to successor nodes! •" The data part is a reference to type E! •" A binary tree node must have links to both its left and right subtrees! The BinaryTree<E> Class! The BinaryTree<E> Class (continued)! Overview of a Binary Search Tree! •" Binary search tree definition! –" A set of nodes T is a binary search tree if either of the following is true! •" T is empty! •" Its root has two subtrees such that each is a binary search tree and the value in the root is greater than all values of the left subtree but less than all values in the right subtree! Overview of a Binary Search Tree (continued)! Searching a Binary Tree! Class TreeSet and Interface Search Tree! BinarySearchTree Class! BST Algorithms! •" Search! •" Insert! •" Delete! •" Print values in order! –" We already know this, it#s inorder traversal! –" That#s why it#s called “in order”! Searching the Binary Tree! •" If the tree is
    [Show full text]
  • Search Trees for Strings a Balanced Binary Search Tree Is a Powerful Data Structure That Stores a Set of Objects and Supports Many Operations Including
    Search Trees for Strings A balanced binary search tree is a powerful data structure that stores a set of objects and supports many operations including: Insert and Delete. Lookup: Find if a given object is in the set, and if it is, possibly return some data associated with the object. Range query: Find all objects in a given range. The time complexity of the operations for a set of size n is O(log n) (plus the size of the result) assuming constant time comparisons. There are also alternative data structures, particularly if we do not need to support all operations: • A hash table supports operations in constant time but does not support range queries. • An ordered array is simpler, faster and more space efficient in practice, but does not support insertions and deletions. A data structure is called dynamic if it supports insertions and deletions and static if not. 107 When the objects are strings, operations slow down: • Comparison are slower. For example, the average case time complexity is O(log n logσ n) for operations in a binary search tree storing a random set of strings. • Computing a hash function is slower too. For a string set R, there are also new types of queries: Lcp query: What is the length of the longest prefix of the query string S that is also a prefix of some string in R. Prefix query: Find all strings in R that have S as a prefix. The prefix query is a special type of range query. 108 Trie A trie is a rooted tree with the following properties: • Edges are labelled with symbols from an alphabet Σ.
    [Show full text]
  • Trees, Binary Search Trees, Heaps & Applications Dr. Chris Bourke
    Trees Trees, Binary Search Trees, Heaps & Applications Dr. Chris Bourke Department of Computer Science & Engineering University of Nebraska|Lincoln Lincoln, NE 68588, USA [email protected] http://cse.unl.edu/~cbourke 2015/01/31 21:05:31 Abstract These are lecture notes used in CSCE 156 (Computer Science II), CSCE 235 (Dis- crete Structures) and CSCE 310 (Data Structures & Algorithms) at the University of Nebraska|Lincoln. This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License 1 Contents I Trees4 1 Introduction4 2 Definitions & Terminology5 3 Tree Traversal7 3.1 Preorder Traversal................................7 3.2 Inorder Traversal.................................7 3.3 Postorder Traversal................................7 3.4 Breadth-First Search Traversal..........................8 3.5 Implementations & Data Structures.......................8 3.5.1 Preorder Implementations........................8 3.5.2 Inorder Implementation.........................9 3.5.3 Postorder Implementation........................ 10 3.5.4 BFS Implementation........................... 12 3.5.5 Tree Walk Implementations....................... 12 3.6 Operations..................................... 12 4 Binary Search Trees 14 4.1 Basic Operations................................. 15 5 Balanced Binary Search Trees 17 5.1 2-3 Trees...................................... 17 5.2 AVL Trees..................................... 17 5.3 Red-Black Trees.................................. 19 6 Optimal Binary Search Trees 19 7 Heaps 19
    [Show full text]
  • AVL Tree, Bayer Tree, Heap Summary of the Previous Lecture
    DATA STRUCTURES AND ALGORITHMS Hierarchical data structures: AVL tree, Bayer tree, Heap Summary of the previous lecture • TREE is hierarchical (non linear) data structure • Binary trees • Definitions • Full tree, complete tree • Enumeration ( preorder, inorder, postorder ) • Binary search tree (BST) AVL tree The AVL tree (named for its inventors Adelson-Velskii and Landis published in their paper "An algorithm for the organization of information“ in 1962) should be viewed as a BST with the following additional property: - For every node, the heights of its left and right subtrees differ by at most 1. Difference of the subtrees height is named balanced factor. A node with balance factor 1, 0, or -1 is considered balanced. As long as the tree maintains this property, if the tree contains n nodes, then it has a depth of at most log2n. As a result, search for any node will cost log2n, and if the updates can be done in time proportional to the depth of the node inserted or deleted, then updates will also cost log2n, even in the worst case. AVL tree AVL tree Not AVL tree Realization of AVL tree element struct AVLnode { int data; AVLnode* left; AVLnode* right; int factor; // balance factor } Adding a new node Insert operation violates the AVL tree balance property. Prior to the insert operation, all nodes of the tree are balanced (i.e., the depths of the left and right subtrees for every node differ by at most one). After inserting the node with value 5, the nodes with values 7 and 24 are no longer balanced.
    [Show full text]