Postorder Binary Search Tree
I want to print postorder of a binary search tree
. Here is my code
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
|
bool BINARY_SEARCH_TREE<T>::insertNode(BSTNode<T> *&p, T newKey)
{
if (p)
{
if (p->key == newKey)
return false;
if (p->key > newKey)
return insertNode(p->left,newKey);
else
return insertNode(p->right,newKey);
}
p = new BSTNode <T>;
if (p == NULL) return false;
p->key = newKey;
p->left = NULL;
p->right = NULL;
return true;
}
template <class T>
bool BINARY_SEARCH_TREE<T>::insert(T newKey)
{
if (insertNode(root,newKey)) return true;
return false;
}
| |
1 2 3 4 5 6 7 8 9 10 11 12 13
|
void BINARY_SEARCH_TREE<T>::LRN(BSTNode<T> *p)
{
if (p == NULL) return;
LNR(p->left);
LNR(p->right);
cout << p->key << " ";
}
template <class T>
void BINARY_SEARCH_TREE<T>::postorder()
{
LRN(root);
}
| |
main.cpp
1 2 3 4 5 6
|
a.insert(40);
a.insert(25);
a.insert(78);
a.insert(10);
a.insert(32);
a.postorder();
| |
i think they good. but it wrong. Need someone help
Is "root" correctly initialized as NULL?
Yes
I cant figure out why it wrong...
Why do you think it's wrong?
Try swap lines to
1 2 3
|
LNR(p->right);
cout << p->key << " ";
LNR(p->left);
| |
this is LNR, not LRN
i have try some cases, only LRN is wrong
I mean put "cout" between "right" and "left".
Ok,, thks, i finally complete it