Advertisement
Guest User

binTree.h

a guest
Jul 1st, 2011
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. #ifndef BIN_TREE_H
  6. #define BIN_TREE_H
  7. #endif
  8.  
  9. class Node {
  10.     public:
  11.     int index;
  12.     int key;
  13.     Node *p;
  14.     Node *left;
  15.     Node *right;
  16.     Node();
  17.     Node(int i, int k, Node *parent, Node *leftChild, Node *rightChild);
  18. };
  19.  
  20. Node::Node() {
  21.     index = key = 0;
  22.     p = left = right = NULL;
  23. }
  24.  
  25. Node::Node(int i, int k, Node *parent, Node *leftChild, Node *rightChild) {
  26.     index = i;
  27.     key = k;
  28.     p = parent;
  29.     left = leftChild;
  30.     right = rightChild;
  31. }
  32.  
  33. class RootedTree {
  34.     private:
  35.     vector<Node> T;
  36.     int n;
  37.     void print(Node *N);
  38.    
  39.     public:
  40.     RootedTree();
  41.     RootedTree(int key);
  42.     bool insert(int index, int key);
  43.     void print();  
  44. };
  45.  
  46. RootedTree::RootedTree() {
  47.     n = 0;
  48. }
  49.  
  50. RootedTree::RootedTree(int key) {
  51.     Node N(T.size(), key, NULL, NULL, NULL);
  52.     T.push_back(N);
  53.     n = 1;
  54. }
  55.  
  56. bool RootedTree::insert(int index, int key) {
  57.     if (index > n-1) return false;
  58.     if (T[index].left == NULL) {
  59.         Node N(n, key, &T[index], NULL, NULL);
  60.         T.push_back(N);
  61.         n++;
  62.         T[index].left = &T[n-1];
  63.         return true;
  64.     } else if (T[index].right == NULL) {
  65.         Node N(n, key, &T[index], NULL, NULL);
  66.         T.push_back(N);
  67.         n++;
  68.         T[index].right = &T[n-1];
  69.         return true;
  70.     }
  71.     return false;
  72. }
  73.  
  74. void RootedTree::print() {
  75.     print(&T[0]);
  76.     cout << endl;
  77. }
  78.  
  79. void RootedTree::print(Node *N) {
  80.     cout << N->key << " ";
  81.     if (N->left != NULL) print(N->left);
  82.     if (N->right != NULL) print(N->right);
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement