Slides - Trees

# Slides - Trees - Trees Binary Search Trees Algorithm...

This preview shows page 1. Sign up to view the full content.

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Trees Binary Search Trees Algorithm searchBST (root, targetKey) // Search a binary search tree for a given value. if (empty tree) return null end if if (targetKey < root) return searchBST (left-subtree, targetKey) else if (targetKey > root) return searchBST (right-subtree, targetKey) else return root end if 5 Algorithm addBST (root, newNode) // Insert node containing new data into BST using recursion. if (empty tree) set root to newNode return newNode end if if (newNode < root) return addBST (left-subtree, newNode) else return addBST (right-subtree, newNode) end if 6 Algorithm daleteBST (root, dltKey) // This algorithm deletes a node from a BST. if (empty tree) return false end if if (dltKey < root) return deleteBST (left-subtree, dltKey) else if (dltKey > root) return deleteBST (right-subtree, dltKey) else if (no left-subtree) make right-subtree the root return true else if (no right-subtree) make left-subtree the root 7 return true else save root in deleteNode set largest to largestBST (left-subtree) move data in largest to deleteNode return deleteBST (left-subtree of deleteNode, key of largest end if end if Algorithm largestBST (root) // This algorithm finds the largest node in a BST. if (right-subtree empty) return (root) end if return largestBST (right-subtree) 8 BST ADT Data Structure typedef struct { int count; NODE* root; } BST_TREE; typedef struct node { int data; struct node* left; struct node* right; } NODE; 9 bool BST_Empty (BST_TREE* tree) { return (tree->count == 0); } BST_TREE* BST_Destroy (BST_TREE* tree) { if (tree) _destroy (tree->root); free (tree); return NULL; } void _destroy (NODE* root) { if (root) { _destroy (root->left); 10 } return; } // _destroy _destroy (root->right); free (root); // if BST Integer Application /* This program builds and prints a BST. Written by: Date: */ #include <stdio.h> #include <stdlib.h> #include “BST-ADT.h” int main (void) { BST_TREE* BSTRoot; int dataIn = 1; 11 printf(“Begin BST Demonstation\n”); BSTRoot = BST_Create ( ); // Build Tree printf(“Enter a list of positive integers;\n”); printf(“Enter a negative number to stop.\n”); do { printf(“Enter a number: ”); scanf(“%d”, &dataIn); if (dataIn > -1) BST_Insert (BSTRoot, dataIn); } while (dataIn > -1); printf(“\nBST contains:\n”); BST_Traverse (BSTRoot); printf(“\nEnd BST Demostration\n”); return 0; // main 12 } ...
View Full Document

## This note was uploaded on 12/28/2010 for the course CSC CSC1110 taught by Professor Cjyuan during the Fall '06 term at CUHK.

Ask a homework question - tutors are online