// .cpp :
//
#include "stdafx.h"
#include <queue>
using namespace std;
typedef struct binary_tree
{
int val;
binary_tree* left;
binary_tree* right;
}BINARY_TREE;
BINARY_TREE* tree = NULL;
void create_binatree_node(BINARY_TREE** ptr, int v)
{
BINARY_TREE* ptr1 = new BINARY_TREE;
ptr1->val = v;
ptr1->left = NULL;
ptr1->right = NULL;
*ptr = ptr1;
}
void create_binatree()
{
tree = new BINARY_TREE;
tree->val = 8;
tree->left = NULL;
tree->right = NULL;
BINARY_TREE* ptr = tree;
create_binatree_node(&(ptr->left),6);
create_binatree_node(&(ptr->right),10);
ptr = ptr->left;
create_binatree_node(&(ptr->left),5);
create_binatree_node(&(ptr->right),7);
BINARY_TREE* ptr5 = ptr->left;
create_binatree_node(&(ptr5->left),1);
create_binatree_node(&(ptr5->right),2);
BINARY_TREE* ptr7 = ptr->right;
create_binatree_node(&(ptr7->left),3);
create_binatree_node(&(ptr7->right),4);
ptr = tree->right;
create_binatree_node(&(ptr->left),9);
create_binatree_node(&(ptr->right),11);
BINARY_TREE* ptr9 = ptr->left;
create_binatree_node(&(ptr9->left),12);
create_binatree_node(&(ptr9->right),13);
BINARY_TREE* ptr11 = ptr->right;
create_binatree_node(&(ptr11->left),14);
create_binatree_node(&(ptr11->right),15);
}
void destory_tree(BINARY_TREE* ptr)
{
if (ptr == tree)
{
printf("destroy tree (after order): \n");
}
if (NULL == ptr)
{
return;
}
destory_tree(ptr->left);
destory_tree(ptr->right);
printf("%d ", ptr->val);
delete ptr;
ptr = NULL;
}
void print_layer()
{
printf("traverse by layer:\n");
queue<BINARY_TREE*> s;
BINARY_TREE* ptr = tree;
s.push(ptr);
int size = s.size();
int index = 0;
ptr = s.front();
while(ptr != NULL)
{
if (ptr->left != NULL)
{
s.push(ptr->left);
index++;
}
if (ptr->right != NULL)
{
s.push(ptr->right);
index++;
}
printf("%d ", ptr->val);
s.pop();
size--;
if (0 == size)
{
printf("\n");
size = index;
index = 0;
}
if (!s.empty())
{
ptr = s.front();
}
else
{
ptr = NULL;
}
}
printf("\n");
}
void mirror_binarytree(BINARY_TREE* ptr)
{
if (ptr == tree)
{
printf("mirror binary tree:\n");
}
if (NULL == ptr)
{
return;
}
mirror_binarytree(ptr->left);
mirror_binarytree(ptr->right);
BINARY_TREE* tmp = ptr->left;
ptr->left = ptr->right;
ptr->right = tmp;
}
int _tmain(int argc, _TCHAR* argv[])
{
create_binatree();
print_layer();
mirror_binarytree(tree);
print_layer();
destory_tree(tree);
return 0;
}