TreeSort question

Hey guys, I am trying to accomplish my TreeSort task, but my output is not able to run successfully.

Input:
Ada Rodriguez
Jeffery Mendez
Rosa Jefferson
Lester Hart
Eunice Moran
Ina Wilkins
Nettie Bowman
Belle Cole

Expected output:
Ada Rodriguez
Belle Cole
Eunice Moran
Ina Wilkins
Jeffery Mendez
Lester Hart
Nettie Bowman
Rosa Jefferson

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
  #include <iostream>
#if !defined(nullptr)
#define nullptr NULL
#endif
using namespace std;

class TreeNode {
// private:
//   TreeNode *root;
public:
  string data;
  TreeNode *left;
  TreeNode *right;

  TreeNode(string element = " ") {
       data = element;
       left = nullptr;
       right = nullptr;
    }

  TreeNode(string element, TreeNode *lt, TreeNode *rt){
    //Your code here
    data = element;
    left = lt;
    right = rt;
  }
  void insert(int x, TreeNode *&t);
  void treeSort(string arr[], int n);
};

void insert(string x, TreeNode *&t) {
  if(t == NULL) {
    t = new TreeNode;
    t -> data = x; 
    t -> left = NULL;
    t -> right = NULL;
    return;
  } else if(x[0]<t->data[0]) {
    insert(x, t->left);
  } else {
    insert(x, t->right);
  }
}


void treeSort(string arr[], int n) {
  TreeNode *t = NULL;
  // t = insert(arr[0],);
  for(int i=0; i<n; i++) {
    insert(arr[i], t);
  }
}

int main() {
  string arr[] = {"Ada Rodriguez", "Rosa Jefferson", "Jeffery Mendez", "Lester Hart", "Eunice Moran", "Ina Wilkins", "Nettie Bowman", "Belle Cole"};

  int n = sizeof(arr)/sizeof(arr[0]);

  treeSort(arr, n);

  for(int i=0; i<n; i++) {
    cout << arr[i] << endl;
  }
  return 0;
}
Last edited on
Why don't you set a breakpoint in your insert function and step through the code and see what happens. Alternatively you can add the output statements to see how the variables change.
Topic archived. No new replies allowed.