#includeusing namespace std; class tree; class node { private: int data; node *left; node *right; public: node(); node(int val); friend class tree; }; node::node() : data(0), left(NULL), right(NULL) { } node::node(int val) : data(val), left(NULL), right(NULL) { } class tree { private: node *root; public: // construct & destruct tree(); ~tree(); // creation void add_node(int val); // deletion void del_node(int val); void clear(node *trav); void clear() { clear(root); root = NULL; } // display void inorder(node *trav); void inorder() { inorder(root); } void preorder(node *trav); void preorder() { preorder(root); } void postorder(node *trav); void postorder() { postorder(root); } // others int height(node *trav); int height() { int ht = height(root); return ht; } node* search(int val); }; // construct & destruct tree::tree() { root = NULL; } tree::~tree() { clear(); } // creation void tree::add_node(int val) { node *newnode = new node(val); if(root == NULL) // tree is empty root = newnode; else // tree is not empty { node *trav = root; while(1) { if(val < trav->data) { // add node to the left if(trav->left == NULL) { trav->left = newnode; break; } else trav = trav->left; } else { // add node to the right if(trav->right == NULL) { trav->right = newnode; break; } else trav = trav->right; } } } } // deletion void tree::del_node(int val) { } void tree::clear(node *trav) { if(trav==NULL) return; clear(trav->left); clear(trav->right); delete trav; } // display void tree::inorder(node *trav) { if(trav==NULL) return; inorder(trav->left); cout << trav->data << " "; inorder(trav->right); } void tree::preorder(node *trav) { if(trav==NULL) return; cout << trav->data << " "; preorder(trav->left); preorder(trav->right); } void tree::postorder(node *trav) { if(trav==NULL) return; postorder(trav->left); postorder(trav->right); cout << trav->data << " "; } // others int tree::height(node *trav) { if(trav==NULL) return 0; int ht_left = height(trav->left); int ht_right = height(trav->right); int max = ht_left > ht_right ? ht_left : ht_right; return max+1; } node* search(int val) { return NULL; } int main() { tree t; t.add_node(10); t.add_node(5); t.add_node(3); t.add_node(15); t.add_node(18); t.add_node(8); t.add_node(12); cout << "pre order : "; t.preorder(); cout << endl; cout << "in order : "; t.inorder(); cout << endl; cout << "post order : "; t.postorder(); cout << endl; int h = t.height(); cout << "height : " << h << endl; return 0; }
Thursday, October 15, 2009
Code to implement a tree (excercise done in cdac)
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment