二叉树的拷贝和释放

#define _CRT_SECURE_NO_WARNGINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct bintree
{
char c;
struct bintree * lchild;
struct bintree * rchild;
}bintree;


//遍历二叉树
void Recursion(bintree* node)
{
if (node == NULL)
{
return;
}
//printf("%c ", node->c);
//先序遍历
Recursion(node->lchild);
//中序遍历
//printf("%c ", node->c);
Recursion(node->rchild);
//后序遍历
printf("%c ", node->c);
}

//拷贝二叉树,从下往上拷贝
bintree *CopyBinaryTree(bintree* node)
{
if (node == NULL)
{
return NULL;
}
if (node->lchild)
{
node->lchild = CopyBinaryTree(node->lchild);
}
if (node->rchild)
{
node->rchild = CopyBinaryTree(node->rchild);
}

bintree *newnode = (bintree*)malloc(sizeof(bintree));
newnode->c = node->c;
newnode->lchild = node->lchild;
newnode->rchild = node->rchild;
return newnode;
}

void ReleaseTree(bintree* node)
{
if (node == NULL)
{
return;
}
ReleaseTree(node->lchild);
ReleaseTree(node->rchild);
free(node);
node = NULL;
}


int main(void)
{
//初始化树结点
bintree root = { 'A', NULL, NULL };
bintree ch1 = { 'B', NULL, NULL };
bintree ch2 = { 'C', NULL, NULL };
bintree ch3 = { 'D', NULL, NULL };
bintree ch4 = { 'E', NULL, NULL };
bintree ch5 = { 'F', NULL, NULL };
bintree ch6 = { 'G', NULL, NULL };
bintree ch7 = { 'H', NULL, NULL };
bintree ch8 = { 'I', NULL, NULL };

root.lchild = &ch1;
root.rchild = &ch2;
ch1.rchild = &ch3;
ch2.lchild = &ch4;
ch3.lchild = &ch5;
ch3.rchild = &ch6;
ch4.lchild = &ch7;
ch4.rchild = &ch8;
//遍历打印树结点
Recursion(&root);

//拷贝二叉树
printf("\n");
bintree* Newnode = CopyBinaryTree(&root);
Recursion(Newnode);

//释放二叉树
ReleaseTree(Newnode);
system("pause");
return 0;
}

posted on 2016-08-08 20:33  A-祥子  阅读(279)  评论(0)    收藏  举报

导航