Binary Search Trees

 

Objectives:

  • Define Binary Search Trees (BST)
  • Describe Binary Search Algorithm
  • Explain an in-order traversal of a BST
  • Describe an unbalanced BST
  • Describe how to balance a BST

Binary Search Tree:

A binary search tree (BST) is a binary tree where each node has a Comparable key (and an associated value) and satisfies the restriction that the key in any node is larger than the keys in all nodes in that node's left subtree and smaller than the keys in all nodes in that node's right subtree

Binary Search Tree:

A binary search tree (BST) is a binary tree where...
smaller nodes go on the left and larger nodes go on the right.

Question:

What is the maximum number of links a node in a BST can have?

Answer

What is the maximum number of links a node in a BST can have?

 

2

 

It has at maximum a left and right node NOT an indefinite number of children

Why use a BST?

Remember...

 Each comparison allows the operations to skip about half of the tree

Question

What is the big O to Search, Insert, or Delete in a BST?

Answer

Worst case is O(n)

Typical case is closer to O(log n)

Search...

  • Check to see if current node is searched node
  • If not, if value is bigger go right
  • If not, if value is smaller go left

Question: How does this compare to binary search in a sorted array?

Insert...

  • Check to see if current node is bigger or smaller than pushed value, move down the tree accordingly
  • Continue the same process until there is no node in the next position
  • Insert node at that new position

Question: How does this compare to binary search in a sorted array?

Delete...

3 possible cases:

  • No Children
    • Remove the node from the tree
  • 1 Child
    • Remove the node and replace it with it's child
  • 2 Children
    • choose either the in-order successor (right sub-trees left most child),
    • or the in-order predecessor (left sub-tree's right most child)
    • copy that element into the position being removed

The 2 children case is the complex case

Question: How does this compare to binary search in a sorted array?

BST In-order Traversal

function InOrder(BST, visit)
    if BST.left
        InOrder(BST.left, visit)
    visit(BST.value)
    if BST.right
        InOrder(BST.right, visit)

Priority Queue

In computer science, a priority queue is an abstract data type which is like a regular queue or stack data structure, but where additionally each element has a "priority" associated with it. In a priority queue, an element with high priority is served before an element with low priority.

Can we use a BST to implement a priority Queue? how?

Balancing BST

  • Grab the middle node, call it the root, and balance from there

Binary Search Trees

 

Objectives:

  • Define Binary Search Trees (BST)
  • Describe Binary Search Algorithm
  • Explain an in-order traversal of a BST
  • Describe an unbalanced BST
  • Describe how to balance a BST
Made with Slides.com