本文介绍: 1.二叉树各个节点度的个数。请编程实现二叉树的操作。1.二叉树的先序遍历。1.二叉树的中序遍历。1.二叉树的后序遍历。
一、二叉树相关练习
请编程实现二叉树的操作
1.二叉树的创建
2.二叉树的先序遍历
3.二叉树的中序遍历
4.二叉树的后序遍历
5.二叉树各个节点度的个数
6.二叉树的深度
代码:
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
typedef struct node//定义二叉树节点结构体
{
int data;
struct node *left;
struct node *right;
}*binary;
binary create_node()//创建节点并初始化
{
binary s=(binary)malloc(sizeof(struct node));
if(NULL==s)
return NULL;
s->data=0;
s->left=NULL;
s->right=NULL;
return s;
}
binary binary_tree()
{
int element;
printf("please enter element(end==0):");
scanf("%d",&element);
if(0==element)
return NULL;
binary tree=create_node();
tree->data=element;
tree->left=binary_tree();
tree->right=binary_tree();
return tree;
}
void first_output(binary tree)
{
if(tree==NULL)
return;
printf("%d ",tree->data);
first_output(tree->left);
first_output(tree->right);
}
void mid_output(binary tree)
{
if(NULL==tree)
return;
mid_output(tree->left);
printf("%d ",tree->data);
mid_output(tree->right);
}
void last_output(binary tree)
{
if(NULL==tree)
return;
last_output(tree->left);
last_output(tree->right);
printf("%d ",tree->data);
}
void limit_tree(binary tree,int *n0,int *n1,int *n2)
{
if(NULL==tree)
return;
if(tree->left&&tree->right)
++*n2;
else if(!tree->left && !tree->right)
++*n0;
else
++*n1;
limit_tree(tree->left,n0,n1,n2);
limit_tree(tree->right,n0,n1,n2);
}
int high_tree(binary tree)
{
if(NULL==tree)
return 0;
int left=1+high_tree(tree->left);
int right=1+high_tree(tree->right);
return left>right?left:right;
}
int main(int argc, const char *argv[])
{
binary tree=binary_tree();//创建二叉树
first_output(tree);//先序遍历
puts("");
mid_output(tree);//中序遍历
puts("");
last_output(tree);//后序遍历
puts("");
int n0=0,n1=0,n2=0;
limit_tree(tree,&n0,&n1,&n2);//计算各个度的节点的个数;
printf("n0=%d,n1=%d,n2=%dn",n0,n1,n2);
int high=high_tree(tree);//计算二叉树深度;
printf("the high of the binary tree is:%dn",high);
return 0;
}
以下图二叉树为例运行结果:
二叉树图:
运行:
原文地址:https://blog.csdn.net/Dai_yahong/article/details/136073414
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_68241.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。