Binary Search Tree Help

I can't get the output right.

Instructions: Given array: string Months[12]={"JAN","FEB",......"DEC"}; write a program to (a) insert data in array Months to a BST (b) display data in alphabetical order. (c) display only the leaves of the tree. (d) display nodes with only one child.

#include<iostream>
#include<string>
#include<iomanip>

using namespace std;

class BST
{
private:struct NODE
{
string month;
NODE *left;
NODE *right;
};
NODE *root;

public:BST()
{
root = NULL;
}
void insert(string x, NODE *&p)
{
if (p == NULL)
{
p = new(NODE); p->month = x;
p->left = p->right = NULL;
}

else
{
if (x < p->month)insert(x, p->left);
if (x > p->month)insert(x, p->right);
}
}
//Display the tree using inorder traversal: (LC)(P)(RC)
void Display(NODE *p)
{
if (p != NULL)
{//inorder:(LC)(P)(RC)
Display(p->left); //LC
cout << p->month << " ";//P
Display(p->right);
}
}
//Display the tree sideways
void DisplaySideways(NODE *p, int space)
{
if (p != NULL)
{
DisplaySideways(p->right, space += 6);
cout << setw(space) << p->month << endl;
DisplaySideways(p->left, space);
}
}
void CountNodes(int &n, NODE *p)
{
//Use preorder: (P)(LC)(RC)
if (p != NULL)
{
n++; //P
CountNodes(n, p->left); //LC
CountNodes(n, p->right); //RC
}
}
void CountLeaves(int& n, NODE *p)
{
if (p != NULL)
{
if (p->left == NULL && p->right == NULL)n++;
CountLeaves(n, p->left);
CountLeaves(n, p->right);
}
}
void CountNodes(int &n){ CountNodes(n, root); }
void insert(string x){ insert(x, root); }
void Display() { Display(root); }
void DisplaySideways(int sp){ DisplaySideways(root, sp); }
void CountLeaves(int &n){ CountLeaves(n, root); }
};//End of class

int main()
{
BST t;
string Months[12] = { "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER" };
for (int i = 0; i < 12; ++i)
{
t.insert(Months[i]);
}
cout << "Display data in alphabetical order: ";
t.Display();

//Display the tree sideways
cout << "This is the tree sideways\n";
t.DisplaySideways(0);

//Count number of nodes
int n = 0;
t.CountNodes(n);
cout << "There are " << n << " nodes in the tree. \n";

//Count the number of leaves
int leaves = 0;
t.CountLeaves(leaves);
cout << "There are " << leaves << " leaves in the tree. \n";

//Terminate program
system("pause");
return 0;
}
1
2
3
DisplaySideways(p->right, space + 6);
cout << string(space, ' ') << p->month << endl;
DisplaySideways(p->left, space + 6);
Topic archived. No new replies allowed.