How to create nodes directly through constructor? (Binary Search Tree)

Hello,

I created a binary search tree with a three-parameter constructor below, however I misunderstood my assignment because I was apparently supposed to "create the nodes directly through the constructor," so instead of doing Insert(root, 3); as I did, I'm to do something along the lines of root = new TNode(7, left, right); in the main function. How can I change my code to accommodate this change?

Thanks in advance!

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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <iostream>
using namespace std;

struct TNode
{
	int data;
    TNode* left;
    TNode* right;
    TNode(int data, TNode* left = NULL, TNode* right = NULL);
    TNode* Insert(int data);
};

TNode::TNode(int data, TNode* left, TNode* right)
{
    this->data = data;
    this->left = left;
    this->right = right;
}

TNode* GetNewNode(int data)
{
	TNode* newNode = new TNode(data, NULL, NULL);

	return newNode;
}

TNode* Insert(TNode* root, int data)
{
	if(root == NULL)
	{
		root = GetNewNode(data);

		return root;
	}

	if(data <= root->data)
	{
		root->left = Insert(root->left, data);
	}

	else
	{
		root->right = Insert(root->right, data);
	}

	return root;
}

int treeSize(TNode* root)
{
	if(root == NULL)
	{
		return 0;
	}

	else
	{
		return treeSize(root->left) + treeSize(root->right) + 1;
	}
}

void inOrder(TNode* root)
{
    if(root->left != NULL)
    {
        inOrder(root->left);
    }

    cout << root->data << " ";

    if(root->right != NULL)
    {
        inOrder(root->right);
    }
}

int main()
{
	TNode* root = NULL;
    root = Insert(root, 5);
    Insert(root, 3);
    Insert(root, 9);
    Insert(root, 1);
    Insert(root, 4);
    Insert(root, 6);

	inOrder(root);

    cout << endl << "There are " << treeSize(root) << " nodes in this tree." << endl;
}
Last edited on
you're almost there, you just have to use the 3 argument ctor a bit more in your program, this post (particularly lines 63, 76 and 91) might give you some ideas:
http://www.cplusplus.com/forum/beginner/210745/#msg988500
Hmm.. So you're referring to:

63: Node* temp = new Node(data, nullptr, m_first);
76: Node* temp = new Node(data, data_checker, data_checker -> m_next);
91: Node* temp = new Node(data, m_last, nullptr);

But I'm not exactly sure what you mean. :/
Topic archived. No new replies allowed.