all about C++ and PHP
/* /* * File: main.cpp * Author: asit * * Created on 24 September, 2011, 2:14 PM */ #include #include #include #include #include #include using namespace std; /* * */ struct node { int id; string name; node *left; node *right; node():id(0),name(""),left(NULL), right(NULL) {} node(int id, string name):id(id), name(name), left(NULL), right(NULL) {} }; typedef pair emp_det; class BinarySearchTree { node *root; public: BinarySearchTree():root(NULL) {} void addNode(int dt, string nm) { node *temp = NULL; if(root==NULL) { temp = new node; temp->id = dt; temp->name = nm; root = temp; } else { temp = root; while(true) { if(temp->id >= dt) { if(temp->left == NULL) { temp->left = new node(dt,nm); break; } else temp = temp->left; } else { if(temp->id < dt) { if(temp->right == NULL) { temp->right = new node(dt, nm); break; } else temp = temp->right; } } } } } void sort(vector &list) { node *temp = NULL; stack st; temp = root; while(true) { if(temp != NULL) { st.push(temp); temp = temp->left; } else { if(st.empty()) break; temp = st.top(); st.pop(); list.push_back(emp_det(temp->id, temp->name)); temp = temp->right; } } } }; int main(int argc, char** argv) { emp_det arr[] = { emp_det(4, "A"), emp_det(23,"B"), emp_det(10,"C"), emp_det(65,"D"), emp_det(43,"E"), emp_det(89,"F"), emp_det(77,"G"), emp_det(98,"H"), emp_det(76,"I"), emp_det(56,"J") }; BinarySearchTree bst; for(int i=0; i<10; i++) bst.addNode(arr[i].first, arr[i].second); vector list; bst.sort(list); vector ::iterator it; for(it = list.begin(); it != list.end(); it++) cout<<(*it).first<<" "<<(*it).second<
No comments:
Post a Comment