Binary Search Tree, cannot do traversal
Posted
by
ihm
on Stack Overflow
See other posts from Stack Overflow
or by ihm
Published on 2012-06-02T04:26:16Z
Indexed on
2012/06/02
4:41 UTC
Read the original article
Hit count: 165
Please see BST codes below. It only outputs "5". what did I do wrong?
#include <iostream>
class bst {
public:
bst(const int& numb) : root(new node(numb)) {}
void insert(const int& numb) {
root->insert(new node(numb), root);
}
void inorder() {
root->inorder(root);
}
private:
class node {
public:
node(const int& numb) : left(NULL), right(NULL) {
value = numb;
}
void insert(node* insertion, node* position) {
if (position == NULL) position = insertion;
else if (insertion->value > position->value)
insert(insertion, position->right);
else if (insertion->value < position->value)
insert(insertion, position->left);
}
void inorder(node* tree) {
if (tree == NULL)
return;
inorder(tree->left);
std::cout << tree->value << std::endl;
inorder(tree->right);
}
private:
node* left;
node* right;
int value;
};
node* root;
};
int main() {
bst tree(5);
tree.insert(4);
tree.insert(2);
tree.insert(10);
tree.insert(14);
tree.inorder();
return 0;
}
© Stack Overflow or respective owner