二叉树的复制

和二叉树的建立相似

代码入下: 

#include<bits/stdc++.h>
#pragma execution_character_set("utf-8")
using namespace std;
typedef struct BiTNode{
	char data;
	struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree; 

void createBiTree(BiTree &t){
	char c;
	cin>>c;
	if(c=='#')
		t = NULL;
	else{
		t = new BiTNode;
		t->data = c;
		createBiTree(t->lchild);
		createBiTree(t->rchild);
	}
}

void Copy(BiTree t,BiTree &newt){
	if(t==NULL){
		newt = NULL;
		return;
	}
	else{
		newt = new BiTNode;
		newt->data = t->data;
		Copy(t->lchild,newt->lchild);
		Copy(t->rchild,newt->rchild);
	}
}

void PreOrder(BiTree t){
	if(t==NULL)
		return;
	cout<<t->data<<' ';
	PreOrder(t->lchild);
	PreOrder(t->rchild);
}

int main(){
	BiTree t,newt;
	createBiTree(t);
	Copy(t,newt);
	cout<<"模版二叉树先序遍历序列为:";
	PreOrder(t);
	cout<<endl<<"复制后的二叉树先序遍历序列为:";
	PreOrder(newt);
	return 0;
}

测试结果:

假设我们要建立一个如下图所示的二叉树,#代表空节点,按照前序遍历顺序二叉树表示为:ab##c##

 

运行结果如下: 

以下是二叉树复制的 C 语言代码: ```c #include <stdio.h> #include <stdlib.h> // 二叉树结构体 struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; // 复制二叉树函数 struct TreeNode* copyTree(struct TreeNode* root) { if (root == NULL) { return NULL; } struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode)); newNode->val = root->val; newNode->left = copyTree(root->left); newNode->right = copyTree(root->right); return newNode; } // 创建二叉树函数 struct TreeNode* createTree() { int val; scanf("%d", &val); if (val == -1) { return NULL; } struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode)); root->val = val; root->left = createTree(); root->right = createTree(); return root; } // 先序遍历函数 void preOrder(struct TreeNode* root) { if (root == NULL) { return; } printf("%d ", root->val); preOrder(root->left); preOrder(root->right); } int main() { printf("请输入二叉树的节点值,-1表示空节点:\n"); struct TreeNode* root = createTree(); printf("原二叉树先序遍历结果为:\n"); preOrder(root); printf("\n"); struct TreeNode* newRoot = copyTree(root); printf("复制后的二叉树先序遍历结果为:\n"); preOrder(newRoot); printf("\n"); return 0; } ``` 在上述代码中,我们定义了一个结构体 `TreeNode`,表示二叉树的节点,包含了节点值 `val`,左子节点指针 `left` 和右子节点指针 `right`。其中,复制二叉树的函数 `copyTree` 使用了递归的方式进行复制。创建二叉树的函数 `createTree` 使用了递归的方式进行输入,遇到 -1 表示该节点为空。先序遍历函数 `preOrder` 使用了递归的方式进行遍历。 在 `main` 函数中,我们先使用 `createTree` 函数创建一个二叉树,并使用 `preOrder` 函数进行先序遍历。然后,我们使用 `copyTree` 函数复制二叉树,并使用 `preOrder` 函数进行先序遍历。最后,释放二叉树的内存空间。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小小的香辛料

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值