Docsity

Analog and digital C - Binary Search Trees, Study notes of Digital & Analog Electronics

Partial preview of the text

Download Analog and digital C - Binary Search Trees and more Study notes Digital & Analog Electronics in PDF only on Docsity!

Binary Search Trees

Binary Search Trees

• Key property

– Value at node

  • (^) Smaller values in left subtree
  • (^) Larger values in right subtree

– Example

  • (^) X > Y
  • (^) X < Z Y

X

Z

Iterative Search of Binary

Node Find( Node n, Value^ Tree key) {

while (n != null) {

if (n.data == key) // Found it

return n;

if (n.data > key) // In left subtree

n = n.left;

else // In right

subtree

n = n.right;

return null;

Find( root );

Recursive Search of Binary

Tree

Node Find( Node n, Value key) {

if (n == null) // Not found

return( n );

else if (n.data == key) // Found it

return( n );

else if (n.data > key) // In left

subtree

return Find( n.left );

else // In right subtree

return Find( n.right );

Find( root );

Example Binary Searches

• Find ( 25 )

10 < 25, right 30 > 25, left 25 = 25, found 5 < 25, right 45 > 25, left 30 > 25, left 10 < 25, right 25 = 25, found

Binary Search Properties

• Time of search

– Proportional to height of tree

– Balanced binary tree

  • (^) O( log(n) ) time

– Degenerate tree

  • (^) O( n ) time
  • (^) Like searching linked list / unsorted array

• Requires

– Ability to compare key values

Binary Search Tree –

Insertion

• Algorithm

1. Perform search for value X

2. Search will end at node Y (if X not in tree)

3. If X < Y, insert new leaf X as new left

subtree for Y

4. If X > Y, insert new leaf X as new right

subtree for Y

• Observations

– O( log(n) ) operation for balanced tree

– Insertions may unbalance tree

Example Insertion

• Insert ( 20 )

10 < 20, right 30 > 20, left 25 > 20, left Insert 20 on left 20

Example Deletion (Leaf)

• Delete ( 25 )

10 < 25, right 30 > 25, left 25 = 25, delete

Example Deletion (Internal

Node)

• Delete ( 10 )

Replacing 10 with largest value in left subtree Replacing 5 with largest value in left subtree Deleting leaf