二叉树的递归遍历与复制

来源:互联网 发布:录制视频软件手机 编辑:程序博客网 时间:2024/05/16 14:02
#include <iostream>//定义树的数据结构struct BiTNode{int data;struct BiTNode *lchild, *rchild;};typedef struct BiTNode  BiTNode;typedef struct BiTNode* BiTree;//前序遍历void preOrder(BiTNode *root){if (root == NULL){return;}printf("%d ", root->data);preOrder(root->lchild);preOrder(root->rchild);}//中序遍历void inOrder(BiTNode *root){if (root == NULL){return;}inOrder(root->lchild);printf("%d ", root->data);inOrder(root->rchild);}//后序遍历void posOrder(BiTNode *root){if (root == NULL){return;}posOrder(root->lchild);posOrder(root->rchild);printf("%d ", root->data);}//创建拷贝函数BiTNode* CopyTree(BiTNode *root){BiTNode *newNode = NULL;BiTNode *newLc = NULL;BiTNode *newRc = NULL;if (root == NULL){return NULL;}//拷贝左子树if (root->lchild != NULL){newLc = CopyTree(root->lchild);}else{newLc = NULL;}//拷贝右子树if (root->rchild != NULL){newRc = CopyTree(root->rchild);}else{newRc = NULL;}//创建动态内存newNode = (BiTNode * )malloc(sizeof(BiTNode));if (newNode == NULL){return NULL;}newNode->lchild = newLc;newNode->rchild = newRc;newNode->data = root->data;return newNode;}void main(){BiTNode t1, t2, t3, t4, t5;memset(&t1, 0, sizeof(BiTNode));memset(&t2, 0, sizeof(BiTNode));memset(&t3, 0, sizeof(BiTNode));memset(&t4, 0, sizeof(BiTNode));memset(&t5, 0, sizeof(BiTNode));t1.data = 1;t2.data = 2;t3.data = 3;t4.data = 4;t5.data = 5; t1.lchild = &t2;t1.rchild = &t3;t2.lchild = &t4;t2.rchild = &t5;printf("Old Tree's preOrder:\n");preOrder(&t1);printf("\n");printf("Old Tree's inOrder:\n");inOrder(&t1);printf("\n");printf("Old Tree's posOrder:\n");posOrder(&t1);printf("\n");printf("Old Tree:\n");preOrder(&t1);printf("\n");BiTNode* newTree = CopyTree(&t1);printf("New Tree:\n");preOrder(newTree);system("pause");}

原创粉丝点击