#include <stdio.h>
#include <stdlib.h>
typedef struct BinaryTree {
int value;
struct BinaryTree* Left;
struct BinaryTree* Right;
}BinaryTrees;
void pre_trival(BinaryTrees *p_node) {
if(p_node == NULL)
return;
printf("%d ", p_node -> value);
pre_trival(p_node -> Left);
pre_trival(p_node -> Right);
}
void mid_trival(BinaryTrees *p_node) {
if(p_node == NULL)
return;
mid_trival(p_node -> Left);
printf("%d ", p_node -> value);
mid_trival(p_node -> Right);
}
void hid_trival(BinaryTrees *p_node) {
if(p_node == NULL)
return;
hid_trival(p_node -> Left);
hid_trival(p_node -> Right);
printf("%d ", p_node -> value);
}
void node_tree(BinaryTrees *p_node, int &nums) {
if(p_node == NULL)
return;
if(p_node -> Left == NULL && p_node -> Right == NULL)
nums ++;
node_tree(p_node -> Left, nums);
node_tree(p_node -> Right, nums);
}
int height_tree(BinaryTrees *p_node) {
if(p_node == NULL)
return 0;
int left_height = height_tree(p_node -> Left);
int right_height = height_tree(p_node -> Right);
return left_height > right_height? (left_height + 1) : (right_height + 1);
}
BinaryTrees *Node_copy(BinaryTrees *p_node) {
if(p_node == NULL)
return NULL;
BinaryTrees *node_left = Node_copy(p_node -> Left);
BinaryTrees *node_right = Node_copy(p_node -> Right);
BinaryTrees *new_node = (BinaryTrees *)malloc(sizeof(BinaryTrees));
new_node -> Left = node_left;
new_node -> Right = node_right;
new_node -> value = p_node -> value;
return new_node;
}
void Destory_Tree(BinaryTrees *p_node) {
if(p_node == NULL)
return;
Destory_Tree(p_node -> Left);
Destory_Tree(p_node -> Right);
free(p_node);
}
int main() {
BinaryTrees n1 = {1, NULL, NULL};
BinaryTrees n2 = {2, NULL, NULL};
BinaryTrees n3 = {3, NULL, NULL};
BinaryTrees n4 = {4, NULL, NULL};
BinaryTrees n5 = {5, NULL, NULL};
BinaryTrees n6 = {6, NULL, NULL};
BinaryTrees n7 = {7, NULL, NULL};
BinaryTrees n8 = {8, NULL, NULL};
n1.Left = &n2;
n1.Right = &n3;
n2.Left = &n4;
n2.Right = &n5;
n3.Left = &n6;
n3.Right = &n7;
n4.Left = &n8;
printf("---开始前序遍历---\n");
pre_trival(&n1);printf("\n");
printf("---开始中序遍历---\n");
mid_trival(&n1);printf("\n");
printf("---开始后序遍历---\n");
hid_trival(&n1);printf("\n");
int num_help = 0;
node_tree(&n1, num_help);
printf("---二叉树的叶子数量:%d---\n", num_help);
printf("---二叉树的高度:%d---\n", height_tree(&n1));
printf("---开始拷贝二叉树---\n");
BinaryTrees *new_tree = Node_copy(&n1);
printf("---拷贝二叉树完成---\n");
printf("---开始前序遍历---\n");
pre_trival(new_tree);printf("\n");
printf("---开始销毁二叉树---\n");
Destory_Tree(new_tree);
printf("---销毁二叉树完成---\n");
system("pause");
return 0;
}
C语言二叉树的递归遍历、节点数目、二叉树高度、拷贝及释放
最新推荐文章于 2022-05-15 16:47:05 发布