BST addElement - PowerPoint PPT Presentation

1 / 9
About This Presentation
Title:

BST addElement

Description:

To find the maximum element in the BST, we follow right children until we reach NULL. ... What if they were inserted so that the resulting BST were perfectly balanced? ... – PowerPoint PPT presentation

Number of Views:57
Avg rating:3.0/5.0
Slides: 10
Provided by: uw3
Category:
Tags: bst | addelement | bst

less

Transcript and Presenter's Notes

Title: BST addElement


1
BST addElement
  • To addElement(), we essentially do a find( ).
    When we reach a null pointer, we create a new
    node there.
  • void addElement(Object el, BinaryTreeNode t)
  • if (t null)
  • t new BinaryTreeNode(el, null, null)
  • else if (el lt t.element)
  • addElement(el, t.left)
  • else if (x gt t.element)
  • addElement(x, t.right)
  • else
  • // duplicate do appropriate thing
  • Can be implemented iteratively.

2
findMin, findMax
  • To find the maximum element in the BST, we follow
    right children until we reach NULL.
  • To find the minimum element in the BST, we follow
    left children until we reach NULL.

3
BST remove
  • Removing an item disrupts the tree structure.
  • Basic idea find the node that is to be removed.
    Then fix the tree so that it is still a binary
    search tree.
  • Three cases
  • node has no children
  • node has one child
  • node has two children

4
No children, one child
5
Two children
  • Replace the node with its successor. Then remove
    the successor from the tree.

6
Height of BSTs
  • n-node BST Worst case depth n-1.
  • Claim The maximum number of nodes in a binary
    tree of height h is 2h1 1.
  • Proof The proof is by induction on h. For h
    0, the tree has one node, which is equal to 201
    1.
  • Suppose the claim is true for any tree of height
    h. Any tree of height h1 has at most two
    subtrees of height h. By the induction
    hypothesis, this tree has at most 2 (2h1 1)1
    2h2 1.

7
Height of BSTs, contd
  • If we have a BST of n nodes and height h, then by
    the Claim,
  • n ? 2h1 1.
  • So, h ? log (n1) 1.
  • Average depth of nodes in a tree. Assumptions
    insert items randomly (with equal likelihood)
    each item is equally likely to be looked up.
  • Internal path length the sum of the depths of
    all nodes.

8
Average Depth
  • Let D(n) be the internal path length of some tree
    with n nodes.
  • The left subtree has i nodes, and the right
    subtree has ni1 nodes.
  • D(1) 0
  • D(n) D(i)
  • D(n i 1) n 1

9
  • D(n) ? 1.442 n log n
  • How long does it take to insert the items 1, 2,
    3, , n (in that order) into a BST?
  • What if they were inserted so that the resulting
    BST were perfectly balanced?
Write a Comment
User Comments (0)
About PowerShow.com