二叉树的遍历
作者:
Aqiw
,
2025-04-16 13:44:02
· 河北
,
所有人可见
,
阅读 2
二叉树的遍历
#include <stdio.h>
#include <stdlib.h>
typedef struct btnode
{
int val;
struct btnode* lchild;
struct btnode* rchild;
} btnode;
btnode* create(int val)
{
btnode* newnode = (btnode*)malloc(sizeof(btnode));
if (newnode == NULL)
{
printf("内存分配失败!\n");
return NULL;
}
newnode->val = val;
newnode->lchild = NULL;
newnode->rchild = NULL;
return newnode;
}
btnode* build()
{
int val;
scanf("%d", &val);
if (val == -1)
{
return NULL;
}
btnode* bt = create(val);
bt->lchild = build();
bt->rchild = build();
return bt;
}
void preorder(btnode* bt)
{
if(bt!=NULL)
{
printf("%-4d", bt->val);
preorder(bt->lchild);
preorder(bt->rchild);
}
}
int main()
{
printf("请按照前序遍历的顺序输入二叉树节点的值(用-1表示空节点):\n");
btnode* root = build();
printf("先序遍历结果为:\n");
preorder(root);
return 0;
}