N

#### nin234

posting this question more from a C++ point of view rather than Binary

search tree techniques.

This is is the output of running the program

../a.out

6

5

7

4

8

0

top->k 6

h->k 6

Basically it is only inserting the top or the root of the tree. When I

turn on the debugger gdb. I am able to see the creation of node to

insert 5 in the recursive function insertR. But top->l is still a null

variable. Why is this due to? Is it something to do with static nature

of top

#include <iostream>

//Build a binary tree from user input and print out the tree by

//different traversal techniques and also provide a search function

//

template <class Key> class BST

{

Key k;

BST *l, *r;

static BST *top;

void insertR(Key& , BST *);

void printR (BST *);

public:

void insert (Key& k);

void print ();

BST (Key k) : k (k) {l=0; r = 0;}

BST () {l=0; r=0; k=0;}

};

template <class Key> BST<Key> *BST<Key>::top = 0;

template <class Key> void BST<Key>::insert (Key& k)

{

if (top == 0)

{

top = new BST (k);

return;

}

insertR (k, top);

}

template <class Key> void BST<Key>:rint ()

{

if (top == 0)

return;

std::cout << "top->k " << top->k << std::endl;

printR (top);

std::cout << std::endl;

}

template <class Key> void BST<Key>:rintR (BST *h)

{

if (h == 0)

return;

std::cout << "h->k " << h->k << std::endl;

printR (h->l);

printR (h->r);

}

template <class Key> void BST<Key>::insertR (Key& kl, BST *h)

{

if (h == 0)

{

h = new BST (kl);

return;

}

if (kl < h->k)

insertR (kl, h->l);

if (kl > h->k)

insertR (kl, h->r);

}

int main ()

{

BST<int> tst;

int k;

do {

std::cin >> k;

tst.insert (k);

}

while (k > 0);

tst.print();

}