Traversing a Binary Tree Binary Search Tree Insertion Deleting from a Binary Search Tree
Trees 3 The Binary Search Tree Section 4.3. Binary Search Tree Also known as Totally Ordered Tree...
-
Upload
allison-parks -
Category
Documents
-
view
227 -
download
0
description
Transcript of Trees 3 The Binary Search Tree Section 4.3. Binary Search Tree Also known as Totally Ordered Tree...
Trees 3The Binary Search Tree
Section 4.3
Binary Search Tree Also known as Totally Ordered Tree
Definition: A binary tree B is called a binary search tree iff: There is an order relation ≤ defined for the vertices of B For any vertex v, and any descendant u of v.left, u ≤ v For any vertex v, and any descendent w of v.right, v ≤ w
Binary Search Tree
Which one is NOT a BST?
Binary Search Tree
Consequences: The smallest element in a binary search tree (BST) is the “left-
most” node
The largest element in a BST is the “right-most” node
Inorder traversal of a BST encounters nodes in increasing order
4
2 6
1 3 75
root
Binary Search using BST
Assumes nodes are organized in a totally ordered binary tree Begin at root node Descend using comparison to make left/right decision
if (search_value < node_value) “go to the left child”
else if (search_value > node_value) “go to the right child”
else return true // success Until descending move is impossible Return false (failure)
BST Class Template
BST Class Template (contd.)
Internal functionsused in recursive calls
Pointer passed by reference (why?)
BST: Public members calling private recursive functions
BST: Searching for an element
BST: Search using function objects
BST: Find the smallest element
Tail recursion
BST: Find the biggest element
Non-recursive
BST: Insertion
Before insertionAfter insertion
BST: Insertion (contd.)
Strategy:
•Traverse the tree as in searching for t with contains()
•Insert if you cannot find the element t.
BST: Deletion
Before delete(4)
After delete(4)
Deleting a node with one child
Deletion Strategy: Bypass the node being deleted
BST: Deletion (contd.)
Before delete(2)
After delete(2)
Deleting a node with two children
Deletion Strategy: Replace the node with smallest node in the right subtree
BST: Deletion (contd.)
BST: Lazy Deletion
Another deletion strategy Don’t delete! Just mark the node as deleted. Wastes space But useful if deletions are rare or space is not a
concern.
BST: Destructor
BST: Assignment Operator
BST: Insertion Bias
Start with an empty tree.Insert elements in sorted orderWhat tree do you get?How do you fix it?
BST: Deletion Bias
After large number of alternating insertions and deletions
Why this bias? How do you fix it?