For my project 4 I have to build a Binary Search Tree using Inorder Traversal. I know what it does but I dont know how to go about creating a code for one. This is what I got so far:
Code:
#include<iostream>
using namespace std;
typedef BinNode;
typedef char Elem;
class BinNodePtr
{
private:
Elem it; /*The node's value*/
BinNodePtr*lc; /*Pointer to left child*/
BinNodePtr*rc; /*Pointer to right child*/
public:
/*Two constructors -- with and without initial values*/
BinNodePtr() {lc = rc = NULL;}
BinNodePtr(Elem e, BinNodePtr* l =NULL, BinNode* r =NULL)
{ it = e; lc = l; rc = r; }
~BinNodePtr() {} /*Destructor*/
Elem& val() {return it;}
void setVal(const Elem& e) {it = e;}
inline BinNode*left() const { return lc;}
void setLeft(BinNode*b) {lc = (BinNodePtr*)b;}
inline BinNode*right() const { return rc; }
void setRight(BinNode*b) { rc = (BinNodePtr*)b; }
bool isLeaf() { return (lc == NULL) && (rc == NULL); }
};
void treeInsert(TreeNode *&root, string newItem) {
if ( root == NULL ) {
root = new TreeNode( newItem );
return;
}
else if ( newItem < root->item ) {
treeInsert( root->left, newItem );
}
else {
treeInsert( root->right, newItem );
}
}
void inorder(BinNode* subroot){
if(subroot == NULL) return;
inorder(subroot->left());
visit(subroot);
inorder(subroot->right());
}
bool treeContains( TreeNode *root, string item ) {
if ( root == NULL ) {
return false;
}
else if ( item == root->item ) {
return true;
}
else if ( item < root->item ) {
return treeContains( root->left, item );
}
else {
return treeContains( root->right, item );
}
} // end treeContains()