树2-二叉树拷贝, 遍历, 计算叶子结点和高度
二叉树结点
typedef struct BinaryNode{
char ch;
struct BinaryNode *lChild;
struct BinaryNode *rChild;
} BinaryNode;
//叶子结点的数量
int sum;
二叉树遍历
前序
//递归遍历(前序)
void Recursion(BinaryNode *root){
//中左右
if(root==NULL) return; //root为空return
cout << root->ch;
//左子树
Recursion(root->lChild);
//右子树
Recursion(root->rChild);
}
中序
//递归遍历(中序)
void Recursion2(BinaryNode *root){
if(root==NULL) return; //root为空return
//先遍历左子树
Recursion2(root->lChild);
//再访问遍历根节点
cout << root->ch;
//再遍历右子树
Recursion2(root->rChild);
}
后序
//递归遍历(后序)
void Recursion3(BinaryNode *root){
if(root==NULL) return; //root为空return
//先遍历左子树
Recursion3(root->lChild);
//再遍历右子树
Recursion3(root->rChild);
//再访问遍历根节点
cout << root->ch;
}
求叶子节点的数量
//在成员位置定义一个sum
//求叶子节点的数目(没有子结点)
void CalculateLeafNum(BinaryNode *root){
if(root==NULL) return;
if(root->lChild==NULL && root->rChild==NULL){
sum++;
};
//先遍历左子树
CalculateLeafNum(root->lChild);
//再遍历右子树
CalculateLeafNum(root->rChild);
}
二叉树拷贝
BinaryNode* CopyBinaryTree(BinaryNode *root){
if(root==NULL){
return NULL;
}
//拷贝左子树
BinaryNode *lchild = CopyBinaryTree(root->lChild);
//拷贝右子树
BinaryNode *rchild = CopyBinaryTree(root->rChild);
//创建结点
BinaryNode *newNode = (BinaryNode*)malloc(sizeof(BinaryNode));
newNode->ch = root->ch;
newNode->lChild = lchild;
newNode->rChild = rchild;
return newNode;
}
释放二叉树
void FreeSpaceBinaryTree(BinaryNode* root){
if(root==NULL){
return;
}
//释放左子树
FreeSpaceBinaryTree(root->lChild);
//释放右子树
FreeSpaceBinaryTree(root->rChild);
//释放当前结点
free(root);
}
求二叉树高度
//求二叉树高度
int CalculateTreeDepth(BinaryNode *root){
if(root==NULL) return 0;
int depth = 0;
//求左子树高度
int leftDepth = CalculateTreeDepth(root->lChild);
//求右子树高度
int rightDepth = CalculateTreeDepth(root->rChild);
//比较高度
depth = leftDepth>rightDepth ? leftDepth+1 : rightDepth+1;
return depth;
}
创建二叉树
二叉树结构
void CreateBinaryTree(){
//创建结点
BinaryNode node1 = {'A',NULL,NULL};
BinaryNode node2 = {'B',NULL,NULL};
BinaryNode node3 = {'C',NULL,NULL};
BinaryNode node4 = {'D',NULL,NULL};
BinaryNode node5 = {'E',NULL,NULL};
BinaryNode node6 = {'F',NULL,NULL};
BinaryNode node7 = {'G',NULL,NULL};
BinaryNode node8 = {'H',NULL,NULL};
//建立结点关系
node1.lChild = &node2;
node2.rChild = &node3;
node3.lChild = &node4;
node3.rChild = &node5;
node1.rChild = &node6;
node6.rChild = &node7;
node7.rChild = &node8;
//拷贝二叉树
BinaryNode *root = CopyBinaryTree(&node1);
//前序遍历
cout << "前序遍历: ";
Recursion(root);
cout << endl;
//中序遍历
cout << "中序遍历: ";
Recursion2(root);
cout << endl;
//后序遍历
cout << "后序遍历: ";
Recursion3(root);
cout << endl;
//计算叶子结点数量
CalculateLeafNum(root);
//求二叉树高度
int depth = CalculateTreeDepth(root);
cout << endl;
cout << "树深度为: " << depth << endl;
FreeSpaceBinaryTree(root);
}
调用
int main(){
int sum = 0;
CreateBinaryTree();
cout << endl;
system("pause");
return 0;
}
标签:结点,遍历,二叉树,rChild,NULL,root,BinaryNode
From: https://www.cnblogs.com/HIK4RU44/p/18144389