#include <stdio.h>
#include <stdlib.h>
// 树的结点的结构定义
typedef struct node {
int data;
struct node* Left;
struct node* Right;
} Node;
// 先序遍历 访问根 -> 左子结点 -> 右子结点
void preorder(Node* node) {
if (node != NULL) {
printf("%d\n", node->data);
preorder(node->Left);
preorder(node->Right);
}
}
// 中序遍历 左子结点 -> 访问根 -> 右子结点
void inorder(Node* node) {
if (node != NULL) {
inorder(node->Left);
printf("%d\n", node->data);
inorder(node->Right);
}
}
// 后序遍历 左子结点 -> 右子结点 -> 访问根
void postorder(Node* node) {
if (node != NULL) {
postorder(node->Left);
postorder(node->Right);
printf("%d\n", node->data);
}
}
int main(void)
{
// 创建结点
Node n1;
Node n2;
Node n3;
Node n4;
// 赋值
n1.data = 5;
n2.data = 6;
n3.data = 7;
n4.data = 8;
// 确定各结点的关系
n1.Left = &n2;
n1.Right = &n3;
n2.Left = &n4;
n2.Right = NULL; // 没有子结点就指向 NULL
n3.Left = NULL;
n3.Right = NULL;
n4.Left = NULL;
n4.Right = NULL;
// 遍历结点
printf("先序遍历结果:\n");
preorder(&n1);
printf("中序遍历结果:\n");
inorder(&n1);
printf("后序遍历结果:\n");
postorder(&n1);
return 0;
}
二叉树的结点定义及遍历
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 二叉树(binary tree)是一颗树,其中每个节点都不能有多于两个的儿子。 1.二叉树节点 作为图的特殊形式,...
- 本篇主要介绍自编码这一粗暴、有效的手段。 自编码是一个很有趣的思路,很容易被理解和接受,它替代了传统的特征提取过程...