Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdafx.h"
- #include <vector>
- #include <string>
- #include <iostream>
- #include <sstream>
- #include <algorithm>
- #include <math.h>
- using namespace std;
- // Return the height of a complete k-ary tree with N nodes.
- int Height(unsigned int n /* node count */, unsigned int k /* k array tree */ )
- {
- return (int)ceil( log((double)n*(k-1) + 1 )/log((double)k));
- }
- struct Node
- {
- int Value;
- vector<Node*> Children;
- Node(unsigned int kval, int val = 0) : Value(val), K(kval) {}
- void AddChild(Node * child)
- {
- if ( Children.size() < K )
- {
- Children.push_back(child);
- }
- else
- {
- int i = 0;
- i = 1;
- // We should throw here
- }
- }
- private:
- unsigned int K; // K of K-ary tree
- };
- Node * ConstructTree(int *& values, int * end, unsigned int k, int height)
- {
- if ( height == 0 ) return 0; // Empty tree
- if ( values >= end ) return 0; // We're out of values on the last level
- Node * newNode = new Node(k, values[0]);
- values++;
- unsigned int i;
- for(i = 0; i < k; i++)
- {
- newNode->AddChild(ConstructTree(values, end, k, height-1));
- }
- return newNode;
- }
- // Constructs a complete k-ary tree from given values
- Node * ConstructTree(int * values, unsigned int count, unsigned int k)
- {
- int height = Height(count, k);
- return ConstructTree(values, values+count, k, height);
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- // Pre-order traversal of a 3-ary tree with 13 nodes.
- //1, 2, 5, 6, 7, 3, 8, 9, 10, 4, 11, 12, 13
- int items[] = {1, 2, 5, 6, 7, 3, 4};
- int itemCount = sizeof(items)/sizeof(*items);
- // Construct a 3-ary tree.
- Node * tree = ConstructTree(items, itemCount, 3);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement