#include<stdio.h>
#include<stdlib.h>
/* * 二叉树节点包含数据域,指向左子树的指针,指向右子树的指针 */
typedef struct node
{
int data;
struct node* left;
struct node* right;
}bitree;
/* * 计算二叉树的高度 */
int height(bitree* node) {
if (node==NULL)
return 0;
else
{
// 计算左子树的高度和右子树的高度
int lHeight = height(node->left);
int rHeight = height(node->right); // 返回二者较大者加1
if (lHeight > rHeight)
return(lHeight+1);
else
return(rHeight+1);
}
}
/* * 辅助函数 * 使用给定的数据生成二叉树节点,节点的左子树和右子树均为空 */
bitree* newNode(int data)
{
bitree* node = (bitree*)malloc(sizeof(bitree));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
//先序遍历二叉树
void preorder(bitree* t){
if(t!=NULL){
printf("%d",t->data);
preorder(t->left);
preorder(t->right);
}
}
//中序遍历二叉树
void midorder(bitree* t){
if(t!=NULL){
midorder(t->left);
printf("%d",t->data);
midorder(t->right);
}
}
int main()
{
bitree *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
printf("Height of tree is %d\n", height(root));
printf("先序遍历二叉树\n");
preorder(root);
printf("\n");
printf("中序遍历二叉树\n");
midorder(root);
return 0;
}
简单实现二叉树的构建与遍历
最新推荐文章于 2022-12-15 00:24:49 发布