fork download
  1. #include <iostream>
  2. #include <fstream>
  3. #include <iterator>
  4. #include <vector>
  5.  
  6. #include <iostream>
  7. #include <cstdlib>
  8. #include <fstream>
  9. #include <iomanip>
  10. #include <algorithm>
  11. using namespace std;
  12.  
  13. typedef struct treeNode {
  14.  
  15. treeNode *leftChild;
  16. treeNode *rightChild;
  17. int data;
  18.  
  19. } treeNode;
  20.  
  21.  
  22. void printTree(treeNode*);
  23. int getNodeDepth(treeNode*);
  24. treeNode* insert(treeNode*, int);
  25. treeNode* createNewNode(int);
  26.  
  27. int main()
  28. {
  29.  
  30.  
  31. //read in file here
  32.  
  33.  
  34. treeNode *root = NULL;
  35. root = insert(root, 8);
  36. root = insert(root, 1);
  37. root = insert(root, 90);
  38. root = insert(root, 3);
  39. root = insert(root, 80);
  40. root = insert(root, 6);
  41. root = insert(root, 83);
  42.  
  43. printTree(root);
  44.  
  45. return 0;
  46. }
  47.  
  48.  
  49. /*
  50.  Purpose: Constructs a new node for the tree.
  51.  Inputs: The data for the node.
  52.  Outputs: returns the new node
  53.  */
  54. treeNode* createNewNode(int data)
  55. {
  56. treeNode *newNode = new treeNode;
  57. newNode->data = data;
  58. newNode->leftChild = NULL;
  59. newNode->rightChild = NULL;
  60. return newNode;
  61. }
  62.  
  63. /*
  64.  Purpose: Calculates the depth of a given node using recursion.
  65.  Inputs: The node to check the depth on.
  66.  Outputs: returns the depth
  67.  */
  68. int getNodeDepth(treeNode *node)
  69. {
  70. if (node == NULL) // tree doesn't exist
  71. return(0);
  72.  
  73. return(1 + max(getNodeDepth(node->leftChild), getNodeDepth(node->rightChild)));
  74. }
  75.  
  76.  
  77. /*
  78.  Purpose: Inserts a node into the tree.
  79.  Inputs: The node to be inserted and the data for the node.
  80.  Outputs: returns the inserted node
  81.  */
  82. treeNode* insert(treeNode *node, int data)
  83. {
  84. if (node == NULL)
  85. return createNewNode(data);
  86. else
  87. {
  88. if (data <= node->data)
  89. {
  90. node->leftChild = insert(node->leftChild, data);
  91. }
  92. else
  93. {
  94. node->rightChild = insert(node->rightChild, data);
  95. }
  96. return node;
  97. }
  98. }
  99.  
  100.  
  101. void printTree_(const treeNode* node, int depth)
  102. {
  103. if (node == NULL)
  104. return;
  105.  
  106. for (int i=0; i<depth; ++i)
  107. std:cout.put('~');
  108. std::cout << node->data << '\n';
  109. printTree_(node->leftChild, depth+1);
  110. printTree_(node->rightChild, depth+1);
  111. }
  112. /*
  113.  Purpose: Prints the BST in a horizontal preorder format.
  114.  Inputs: The root node.
  115.  Outputs: nothing
  116.  */
  117. void printTree(treeNode *node)
  118. {
  119. printTree_(node, 0);
  120. }
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
8
~1
~~3
~~~6
~90
~~80
~~~83