Binary Search Trees - PowerPoint PPT Presentation

About This Presentation
Title:

Binary Search Trees

Description:

Lecture 22 Binary Search Trees Inorder Traversal Traverse the tree as LEFT- ROOT- RIGHT void print(Node ptr) { if (ptr != null) { print(ptr.left ... – PowerPoint PPT presentation

Number of Views:227
Avg rating:3.0/5.0
Slides: 9
Provided by: DonS178
Category:

less

Transcript and Presenter's Notes

Title: Binary Search Trees


1
Lecture 22
  • Binary Search Trees

2
Inorder Traversal
  • Traverse the tree as LEFT- ROOT- RIGHT
  • void print(Node ptr)
  • if (ptr ! null)
  • print(ptr.left)
  • cout ltlt ptr.data
  • print(ptr.right)
  • How does this work?

8
12
6
14
10
4
7
3
Preorder Traversal
  • Traverse the tree as ROOT-LEFT-RIGHT
  • void print(Node ptr)
  • if (ptr ! null)
  • cout ltlt ptr.data
  • print(ptr.left)
  • print(ptr.right)

4
Postorder Traversal
  • Traverse the tree as LEFT-RIGHT-ROOT
  • void print(Node ptr)
  • if (ptr ! null)
  • print(ptr.left)
  • print(ptr.right)
  • cout ltlt ptr.data

5
Deleting a node
  • Delete algorithm
  • 3 cases
  • - leaf
  • - make parent's Left or
    Right (as appropriate) NULL
  • - delete me
  • - internal node, 1 child
  • - make parent's Left or
    Right point to my single child
  • - delete me
  • - internal node, 2
    children
  • - go left, then as far
    right as possible to find node
  • with maximal value in
    left subtree (MLS)
  • - swap MLS data into
    original node to be deleted (me)
  • - make MLS's parent's
    Right point to MLS's left
  • - delete MLS

6
Deleting a Node
  • void Remove(Tree root, string s)
  • Tree pos
  • Tree prev
  • Tree deadnode
  • if (root nulll)
  • System.out.println( " " s " is not
    in the tree.)
  • else if (s lt root.myStr)
  • Remove(root.left, s)
  • else if (s gt root.myStr)
  • Remove(root.right, s)
  • ctd...

7
Deleting a Node ctd..
  • else // found the node to remove
  • deadnode root // deadnode could be
    overwritten later
  • if (root.left null)
  • root root.right
  • else if (root.right null)
  • root root.left // will
    actually delete at end
  • else // the node to delete has two
    children
  • // go left once, then as far right
    as possible
  • pos root.left
  • while (pos-gtright ! null)
  • prev pos
  • pos pos.right
  • root.myStr pos.myStr
  • deadnode pos // deadnode no
    longer root

8
Searching a tree
  • bool Search(Node t, string val)
  • if (t null) return false
  • if ( val t.data)
  • return true
  • if (val lt t.data)
  • Search( t.Left,val)
  • else
  • Search( t.Right, val )
  • return true
Write a Comment
User Comments (0)
About PowerShow.com