二叉树的复制
来源:互联网 发布:springmvc找不到js 编辑:程序博客网 时间:2024/05/08 12:10
题目:把一棵二叉树复制到另一棵二叉树
- =》
// * 二叉树的复制 */// * ======================================== */#include "stdio.h"#include "stdlib.h"struct tree { int data; // * 节点数据 */ struct tree *left; // * 指向左子树的指针 */ struct tree *right; // * 指向右子树的指针 */};typedef struct tree treenode; typedef treenode *btree; // * ---------------------------------------- */// * 建立二叉树 */// * ---------------------------------------- */btree createbtree(int *data,int pos) //data为赋值给二叉树的各个节点的值,pos为data数组中的位置{ btree newnode; if ( data[pos] == 0 || pos > 15 ) return NULL; else { newnode = ( btree ) malloc(sizeof(treenode)); newnode->data = data[pos]; newnode->left = createbtree(data,2*pos); newnode->right = createbtree(data,2*pos+1); return newnode; }}// * ---------------------------------------- */// * 二叉树复制 */// * ---------------------------------------- */btree copybtree(btree root){ btree newnode; if ( root == NULL ) return NULL; else { newnode = ( btree ) malloc(sizeof(treenode)); //申请新的二叉树的根节点的空间 newnode->data = root->data; newnode->left = copybtree(root->left); //递归申请空间并把节点的左孩子的值分配给新二叉树对应的节点 newnode->right = copybtree(root->right); //分配右孩子的值<span style="white-space:pre"> return newnode; //返回新二叉树的根节点<span style="white-space:pre"> }}// * ---------------------------------------- */// * 二叉树中序列印 */// * ---------------------------------------- */void printbtree(btree ptr){ if ( ptr != NULL ) { printbtree(ptr->left); printf("[%2d]",ptr->data); printbtree(ptr->right); }}// * ---------------------------------------- */// * 主程式: 建立二叉树后备份它. */// * ---------------------------------------- */void main(){ btree root = NULL; // * 指向原二叉树的根节点的指针 */ btree backup = NULL; // * 复制二叉树的根节点的指针 */ // * 二叉树节点数据 */ int data[16] = { 0, 5, 4, 6, 2, 0, 0, 8, 1, 3, 0, 0, 0, 0, 7, 9 }; root = createbtree(data,1); // * 建立树状结构 */ backup = copybtree(root); // * 复制二叉树 */ printf("原二叉树的节点内容 \n"); printbtree(root); // * 中序列二叉树 */ printf("\n备份二叉树的节点内容 \n"); printbtree(backup); // * 中序列二叉树 */ printf("\n"); // * 换行 */}
0 0
- 二叉树的复制
- 二叉树的复制
- 二叉链表存储的二叉树的复制
- 二叉树的创建、复制、遍历
- 二叉树的递归遍历与复制
- 复制二叉树
- 复制二叉树
- 二叉树采用二叉链表存储,复制二叉树的算法(树的应用)
- 二叉树的创建与遍历&二叉树的高度&二叉树每层结点个数&复制二叉树
- 二叉树5(复制二叉树)
- 复制二叉树(二叉树)
- C++数据结构--二叉树的复制和删除
- 编写复制一颗二叉树的非递归算法
- 复制一棵二叉树的非递归算法
- 基于层次遍历的非递归复制二叉树
- [数据结构] 二叉树的等价判断与复制
- 二叉搜索树的c++实现(含深复制)
- 1021_二叉树的复制和左右子树交换
- git config --global user.email
- Median of Two Sorted Arrays
- (七)scheduler 定时器
- 如何使用CMake配置编译MYGUI3.2.0
- cocos2d-x win32显示中文乱码解决方法
- 二叉树的复制
- HDU 2767 Proving Equivalences(强连通分量)
- IDT系列:(一)初探IDT,Interrupt Descriptor Table,中断描述符表
- (六)制作自定义效果按钮菜单
- Combination Sum II Java
- Android定时执行任务
- FAT学习笔记(四)——Dir Entry
- IDT系列:(二)中断处理过程,使用bochs调试IDT中的中断服务程序
- 隐式动画及 CAlayer position 与 anchorPoint