Advertisement
Guest User

Construct a complete K-ary tree from preorder traversal

a guest
Apr 5th, 2011
3,101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.66 KB | None | 0 0
  1. #include "stdafx.h"
  2. #include <vector>
  3. #include <string>
  4. #include <iostream>
  5. #include <sstream>
  6. #include <algorithm>
  7. #include <math.h>
  8. using namespace std;
  9.  
  10. // Return the height of a complete k-ary tree with N nodes.
  11. int Height(unsigned int n /* node count */, unsigned int k /* k array tree */ )
  12. {
  13.     return (int)ceil( log((double)n*(k-1) + 1 )/log((double)k));
  14. }
  15.  
  16. struct Node
  17. {
  18.     int Value; 
  19.     vector<Node*> Children;
  20.  
  21.     Node(unsigned int kval, int val = 0) : Value(val), K(kval) {}
  22.  
  23.     void AddChild(Node * child)
  24.     {
  25.         if ( Children.size() < K )
  26.         {          
  27.             Children.push_back(child);
  28.         }
  29.         else
  30.         {
  31.             int i = 0;
  32.             i = 1;
  33.             // We should throw here
  34.         }
  35.     }
  36.  
  37. private:
  38.     unsigned int K; // K of K-ary tree
  39. };
  40.  
  41. Node * ConstructTree(int *& values, int * end, unsigned int k, int height)
  42. {
  43.     if ( height == 0 ) return 0; // Empty tree
  44.     if ( values >= end ) return 0; // We're out of values on the last level
  45.  
  46.     Node * newNode = new Node(k, values[0]);
  47.     values++;
  48.  
  49.     unsigned int i;
  50.     for(i = 0; i < k; i++)
  51.     {
  52.         newNode->AddChild(ConstructTree(values, end, k, height-1));
  53.     }
  54.  
  55.     return newNode;
  56. }
  57.  
  58. // Constructs a complete k-ary tree from given values
  59. Node * ConstructTree(int * values, unsigned int count, unsigned int k)
  60. {
  61.     int height = Height(count, k);
  62.     return ConstructTree(values, values+count, k, height);
  63. }
  64.  
  65. int _tmain(int argc, _TCHAR* argv[])
  66. {
  67.     // Pre-order traversal of a 3-ary tree with 13 nodes.
  68.     //1, 2, 5, 6, 7, 3, 8, 9, 10, 4, 11, 12, 13
  69.     int items[] = {1, 2, 5, 6, 7, 3, 4};
  70.     int itemCount = sizeof(items)/sizeof(*items);
  71.  
  72.     // Construct a 3-ary tree.
  73.     Node * tree = ConstructTree(items, itemCount, 3);
  74.  
  75.     return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement