Graph Traversal Discrete Mathematics and Its Applications Baojian Hua [email protected].
Binary Search Tree C and Data Structures Baojian Hua [email protected].
-
date post
20-Dec-2015 -
Category
Documents
-
view
235 -
download
1
Transcript of Binary Search Tree C and Data Structures Baojian Hua [email protected].
Dictionary-like Data Structure A dictionary-like data structure
contains a collection of tuple data: data =<key, value> key is comparable and distinct
supports these operations: new () insert (dict, k, v) lookup (dict, k) delete (dict, k)
We discussed a linear list-based representation of dictionary, this class studies another strategy based on binary trees
Binary Search Tree A binary search tree is a binary tree
satisfies: every node contain data=<key, value>, and
every key is unique all keys in left sub-tree is less than that in
the root all keys in right sub-tree is greater than that
in the root both the left and right sub-trees are also
binary search trees
Operations
All the tree operations we’ve discussed also apply to binary search tree
And BST also supports (as a general dictionary-like data structure): search (bst, key) insert (bst, key, value) delete (bst, key)
Abstract Data Types in C: Interface// in file “bst.h”#ifndef BST_H#define BST_H
#define T Bst_ttypedef struct T *T;
T Bst_new ();T Bst_insert (T t, poly key, poly value);poly Bst_lookup (T t, poly key);
#undef T#endif
Implementation// in file “bst.c”
#include “bst.h”
#define T Bst_t
struct T
{
poly data;
T left;
T right;
};
t
left key rightv
Operations: “lookup”poly Bst_lookup (T t, poly key){ if (0==t) return 0; if (key == t->key) // what’s “==“ ? return t->value; if (key < t->key) // what’s “<“? return lookup (t->left, key); return lookup (t->right, key);}
An Iterative Versionpoly lookup2 (T t, poly key){ if (0==t) return 0; T p = t; while (p && p->key!=key){ // what’s “!=“? if (key < p->key) p = p->left; else p = p->right; }
return p;}
Adding New Bindings:insert (bst t, poly key, poly value) Main idea:
search the tree, if these already exists a key k’==k, then insertion fails
else if tree t==NULL, return a new bst else search a proper position to insert the
tuple <key, value> What’s a proper position?
A Functional VersionT insert (T t, poly key, poly value){ if (!t) return Bst_new2 (0, 0, key, value); switch (compare (key < t->key)) { case “==“: error (“key already exists”); case “<“: return Bst_new2 (insert (t->left, key, value), t->right, t->key, t->value); case “>”: return Bst_new2 (t->left, insert (t->right, key,value),
t->key, t->value); }}