#include <iostream>
using namespace std;
typedef struct bin_tree{
int data;
struct bin_tree *left;
struct bin_tree *right;
} Node;
Node* create_node(int data)
{
Node *n = new Node;
if(n != NULL){
n->data = data;
n->left = NULL;
n->right = NULL;
}
return n;
}
void add_node(Node *r, Node *n, bool is_left)
{
if(is_left){
r->left = n;
}
else{
r->right = n;
}
}
void del_tree(Node *r)
{
if( r == NULL){
return;
}
del_tree(r->left);
del_tree(r->right);
if(r->left == NULL && r->right == NULL){
delete r;
r = NULL;
return;
}
}
void preorder_traverse(Node *r)
{
if(r == NULL){
return;
}
cout << r->data << ", ";
preorder_traverse(r->left);
preorder_traverse(r->right);
}
int main(int argc, char* argv[])
{
Node *root = create_node(100);
Node *n = create_node(50);
add_node(root, n, 1);
Node *n1 = create_node(25);
add_node(n, n1, 1);
n1 = create_node(75);
add_node(n, n1, 0);
n = create_node(150);
add_node(root, n, 0);
n1 = create_node(175);
add_node(n, n1, 0);
n1 = create_node(125);
add_node(n, n1, 1);
n = create_node(110);
add_node(n1, n, 1);
preorder_traverse(root);
del_tree(root);
return 0;
}
Output
100, 50, 25, 75, 150, 125, 110, 175,
Solution
Print out the root (or subtree’s root) value.
Do a preorder traversal on the left subtree.
Do a preorder traversal on the right subtree.
ProblemInformally, a preorder traversal involves walking around the tree in a counterclockwise manner starting at the root, sticking close to the edges, and printing out the nodes as you encounter them. For the tree shown in right figure, the result is 100, 50, 25, 75, 150, 125, 110, 175. Perform a preorder traversal of a binary search tree, printing the value of each node.