不需要写代码的网站开发软件,夸克作文网站,象山县建设管理局网站,微网站第三方平台一、二叉树相关练习
请编程实现二叉树的操作
1.二叉树的创建
2.二叉树的先序遍历
3.二叉树的中序遍历
4.二叉树的后序遍历
5.二叉树各个节点度的个数
6.二叉树的深度
代码#xff1a;
#includestdlib.h
#includestring.h
#includestdio.h
ty…一、二叉树相关练习
请编程实现二叉树的操作
1.二叉树的创建
2.二叉树的先序遍历
3.二叉树的中序遍历
4.二叉树的后序遍历
5.二叉树各个节点度的个数
6.二叉树的深度
代码
#includestdlib.h
#includestring.h
#includestdio.h
typedef struct node//定义二叉树节点结构体
{int data;struct node *left;struct node *right;
}*binary;
binary create_node()//创建节点并初始化
{binary s(binary)malloc(sizeof(struct node));if(NULLs)return NULL;s-data0;s-leftNULL;s-rightNULL;return s;
}
binary binary_tree()
{int element;printf(please enter element(end0):);scanf(%d,element);if(0element)return NULL;binary treecreate_node();tree-dataelement;tree-leftbinary_tree();tree-rightbinary_tree();return tree;
}
void first_output(binary tree)
{if(treeNULL)return;printf(%d ,tree-data);first_output(tree-left);first_output(tree-right);
}
void mid_output(binary tree)
{if(NULLtree)return;mid_output(tree-left);printf(%d ,tree-data);mid_output(tree-right);
}
void last_output(binary tree)
{if(NULLtree)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(NULLtree)return;if(tree-lefttree-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(NULLtree)return 0;int left1high_tree(tree-left);int right1high_tree(tree-right);return leftright?left:right;
}
int main(int argc, const char *argv[])
{binary treebinary_tree();//创建二叉树first_output(tree);//先序遍历puts();mid_output(tree);//中序遍历puts();last_output(tree);//后序遍历puts();int n00,n10,n20;limit_tree(tree,n0,n1,n2);//计算各个度的节点的个数printf(n0%d,n1%d,n2%d\n,n0,n1,n2);int highhigh_tree(tree);//计算二叉树深度printf(the high of the binary tree is:%d\n,high);return 0;
}以下图二叉树为例运行结果
二叉树图 运行