代码
// ConsoleApplication1.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct BINARYNODE
{
char ch;
struct BINARYNODE* left;
struct BINARYNODE* right;
}BinaryNode;
void Recursion(BinaryNode* root) //递归遍历
{
if (root == NULL) return;
Recursion(root->left);
Recursion(root->right);
printf("%c", root->ch);
}
BinaryNode* CopyTree(BinaryNode* root) //拷贝
{
if (root == NULL)
return NULL;
root->left=CopyTree(root->left);
root->right=CopyTree(root->right);
BinaryNode* Node = (BinaryNode*)malloc(sizeof(BinaryNode));
Node->ch = root->ch;
Node->left = root->left;
Node->right = root->right;
return Node;
}
void FreeTree(BinaryNode* root)//释放
{
if (root == NULL)
return;
FreeTree(root->left);
FreeTree(root->right);
free(root);
}
int main(void)
{
BinaryNode b1, b2, b3, b4, b5, b6, b7, b8;
b1.ch = 'A'; b1.left = &b2; b1.right = &b3;
b2.ch = 'B'; b2.left = NULL; b2.right = &b4;
b3.ch = 'F'; b3.left = NULL; b3.right = &b5;
b4.ch = 'C'; b4.left = &b6; b4.right = &b7;
b5.ch = 'G'; b5.left = &b8; b5.right = NULL;
b6.ch = 'D'; b6.left = NULL; b6.right = NULL;
b7.ch = 'E'; b7.left = NULL; b7.right = NULL;
b8.ch = 'H'; b8.left = NULL; b8.right = NULL;
BinaryNode* root = CopyTree(&b1); //将上面创建的二叉树拷贝给root(根)
Recursion(root);
FreeTree(root);
return 0;
}
结果: