// 树的高度.cpp : 定义控制台应用程序的入口点。
// 树的遍历.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <algorithm>
using namespace std;
struct BTNode{
int data;
struct BTNode *lchild, *rchild;
};
typedef struct BTNode BTnode;
typedef struct BTNode* BiTree;
void preOrder(BTNode *root){
if (root == NULL){
return;
}
printf("%d",root->data);
//遍历左子树
preOrder(root->lchild);
//遍历右子树
preOrder(root->rchild);
}
void inOrder(BTNode *root){//中序遍历
if (root == NULL){
return;
}
//遍历左子树
preOrder(root->lchild);
printf("%d", root->data);
//遍历右子树
preOrder(root->rchild);
}
void postOrder(BTNode *root){//后序遍历
if (root == NULL){
return;
}
//遍历左子树
preOrder(root->lchild);
//遍历右子树
preOrder(root->rchild);
printf("%d", root->data);
}
//求树的深度
int Depth(BTNode *T){
int depthleft = 0;
int depthright = 0;
int depthval = 0;
if (T == NULL) return depthval;
depthleft = Depth(T->lchild);
depthright = Depth(T->rchild);
depthval =1+ max(depthleft, depthright);
return depthval;
}
//copy tree 一个一个结点拷贝
BTNode *CopyTree(BTNode *root){
BTNode* newNode = NULL;//new root
BTNode* newlp = NULL;//new left tree
BTNode* newrp = NULL;//new right tree
if (root == NULL){
return NULL;
}
if (root->lchild != NULL){
newlp = CopyTree(root->lchild);//copy left tree
}
else{
newlp = NULL;
}
if (root->rchild != NULL){
newrp = CopyTree(root->rchild);//copy right tree
}
else{
newrp = NULL;
}
//malloc根节点
newNode = (BTNode *)malloc(sizeof(BTNode));
if (newNode == NULL){
return NULL;
}
//指针域拷贝
newNode->lchild = newlp;
newNode->rchild = newrp;
//数据域拷贝
newNode->data = root->data;
return newNode;
}
int _tmain(int argc, _TCHAR* argv[])
{
BTNode t1, t2, t3, t4, t5;
memset(&t1,0,sizeof(BTNode));
memset(&t2, 0, sizeof(BTNode));
memset(&t3, 0, sizeof(BTNode));
memset(&t4, 0, sizeof(BTNode));
memset(&t5, 0, sizeof(BTNode));
t1.data = 1;
t2.data = 2;
t3.data = 3;
t4.data = 4;
t5.data = 5;
//建立关系
t1.lchild = &t2;
t1.rchild = &t3;
t2.lchild = &t4;
t3.lchild = &t5;
//树的遍历
cout << "先序遍历" << endl;
preOrder(&t1);
cout << "中序遍历" << endl;
inOrder(&t1);
cout << "后序遍历" << endl;
postOrder(&t1);
//求树的高度
cout << "树的高度:" << Depth(&t1) << endl;
//copy tree
{
BTNode *root = CopyTree(&t1);
cout << "先序遍历" << endl;
preOrder(root);
cout << "中序遍历" << endl;
inOrder(root);
cout << "后序遍历" << endl;
postOrder(root);
}
return 0;
}
二叉树拷贝
最新推荐文章于 2023-10-17 22:32:51 发布