参考自《从实践中学习嵌入式C语言》
注意结构体中的_tree_node成员,如果写成tree_node会报错:
binary_tree.c: In function ‘construct’:
binary_tree.c:39: warning: passing argument 1 of ‘tree_init’ from incompatible pointer type
binary_tree.c:13: note: expected ‘struct tree_node **’ but argument is of type ‘struct tree_node **’
binary_tree.c:40: error: dereferencing pointer to incomplete type
binary_tree.c:45: warning: assignment from incompatible pointer type
binary_tree.c:53: warning: passing argument 1 of ‘tree_init’ from incompatible pointer type
binary_tree.c:13: note: expected ‘struct tree_node **’ but argument is of type ‘struct tree_node **’
binary_tree.c:54: error: dereferencing pointer to incomplete type
binary_tree.c:58: warning: assignment from incompatible pointer type
例子:建议先从main函数看,构建步骤
1.先初始化一个root
2.初始化一个用来构建二叉树的数组
3.把数组和root输入一个构建函数construct
4.construct里面
4.1第一root的data区域是null的,所以把数组第一个元素给root,即data[0]
4.2后面的data[i]则与第一个元素比较,比它大的在右,比它小的在左。
4.3判断左右后,还要检测子节点是否存在,如果存在,则以同上方法进行遍历;如果不是,则初始化该节点,并把data[i]值给这个节点。
图1:本例构造的二叉树
#include<stdio.h>
#include<stdlib.h>
struct _tree_node
{
char data;
struct _tree_node *lchild;
struct _tree_node *rchild;
};
typedef struct _tree_node tree_node;
//init the binary tree's node
void tree_init(tree_node **node)
{
*node = (tree_node *)malloc(sizeof(tree_node));
(*node)->lchild = (*node)->rchild = NULL;
(*node)->data = 0;
}
//node:root node
//data:node value
void construct(char data, tree_node **node)
{
int i=0;
tree_node *temp_node = *node;
while(temp_node)
{
if(!temp_node->data)
{
//this situation only happen the first time,when the root is NULL
temp_node->data=data;
break;
}
else if(data <= temp_node->data)
{
//if lchild is NULL,then init it
if(!temp_node->lchild)
{
tree_init(&temp_node->lchild);
temp_node->lchild->data = data;
break; //for while loop
}
else //if lchild not NULL,continue to compare it
{
temp_node = temp_node->lchild;
continue; //for while loop
}
}
else if(data>temp_node->data)
{
if(!temp_node->rchild)
{
tree_init(&temp_node->rchild);
temp_node->rchild->data = data;
break;
}
else
{
temp_node = temp_node->rchild;
continue; //for while loop
}
}
}
return;
}
int main()
{
int i;
tree_node *root;
char data[8]={'e','f','h','g','a','c','b','d'};
tree_init(&root);
for(i=0;i<8;i++)
{
construct(data[i],&root);
}
printf("construct finished!\n");
return 0;
}
二叉树是非线性数据结构,如果要转化成线性结构结构,就要对其遍历。参考下文:
http://blog.csdn.net/xzongyuan/article/details/21391775