Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifndef BINARY_TREE
- #define BINARY_TREE
- #include "SimpleQueue.h"
- using namespace std;
- class BinaryTree
- {
- private:
- short int state; //0 - empty, 1 - not empty
- int rowsCount;
- Node *root;
- SimpleQueue *nodesToWalk, *tmpNodes;
- int Power(int n,int power)
- {
- if (power == 0) return 1;
- for (int i=1;i<power;i++)
- n *= n;
- return n;
- }
- public:
- BinaryTree()
- {
- rowsCount = 0;
- state = 0;
- root = 0;
- }
- BinaryTree(int v)
- {
- root = new Node(v);
- rowsCount = 1;
- state = 1;
- }
- bool init(int v)
- {
- root = new Node(v);
- if (root != 0)
- {
- state = 1;
- rowsCount = 1;
- return true;
- }
- return false;
- }
- void Build(int arr[], int elementsCount)
- {
- if (state == 0)
- {
- root = new Node();
- state = 1;
- rowsCount = 1;
- }
- if (elementsCount > 0)
- {
- Node *tmpNode, *tmpChild;
- root->SetVal(arr[0]);
- nodesToWalk = new SimpleQueue(1);
- nodesToWalk->Push(root);
- int i=1;
- int rowNum = 1;
- while (i < elementsCount)
- {
- tmpNodes = new SimpleQueue(Power(2,rowNum));
- while (nodesToWalk->GetState() != 3)
- {
- tmpNode = nodesToWalk->Pop();
- if (i < elementsCount)
- {
- tmpNode->SetLeftChild(new Node(arr[i++]));
- tmpChild = tmpNode->GetLeftChild();
- tmpNodes->Push(tmpChild);
- if (i < elementsCount)
- {
- tmpNode->SetRightChild(new Node(arr[i++]));
- tmpChild = tmpNode->GetRightChild();
- tmpNodes->Push(tmpChild);
- }
- }
- }
- SimpleQueue *delNodes;
- delNodes = nodesToWalk;
- nodesToWalk = tmpNodes;
- delete delNodes;
- rowNum++;
- }
- rowsCount = rowNum;
- }
- }
- void Walk(int rowNum = 1)
- {
- Node *tmpNode;
- nodesToWalk = new SimpleQueue(1);
- nodesToWalk->Push(root);
- if (rowNum < 1) rowNum = 1;
- else if (rowNum > rowsCount) rowNum = rowsCount;
- for (int i = 1; i<= rowsCount; i++)
- {
- tmpNodes = new SimpleQueue(Power(2,i));
- while (nodesToWalk->GetState() != 3)
- {
- tmpNode = nodesToWalk->Pop();
- if (tmpNode->GetLeftChild() != 0) tmpNodes->Push(tmpNode->GetLeftChild());
- if (tmpNode->GetRightChild() != 0) tmpNodes->Push(tmpNode->GetRightChild());
- if (i >= rowNum) cout << tmpNode->GetVal() << ' ';
- }
- SimpleQueue * delNodes = nodesToWalk;
- nodesToWalk = tmpNodes;
- delete delNodes;
- cout << endl;
- }
- }
- int GetRowsCount() {return rowsCount;}
- Node * GetRoot() {return root;}
- };
- #endif
Advertisement
Add Comment
Please, Sign In to add comment