树的概念就不多说了,直接上最简单的代码,关键的一点需要复习下【递归】的概念。
typedef struct node
{
int data;
struct node *left;
struct node *right;
}NODE_T,*PNODE_T;
/*
先序遍历:根->左->右
*/
void preorder(PNODE_T pNode)
{
if(NULL != pNode)
{
printf(" %d",pNode->data);
preorder(pNode->left);
preorder(pNode->right);
}
}
/*
中序遍历:左->根->右
*/
void inorder(PNODE_T pNode)
{
if(NULL != pNode)
{
inorder(pNode->left);
printf(" %d",pNode->data);
inorder(pNode->right);
}
}
/*
后序遍历:左->右->根
*/
void postorder(PNODE_T pNode)
{
if(NULL != pNode)
{
postorder(pNode->left);
postorder(pNode->right);
printf(" %d",pNode->data);
}
}
void test_binary_tree(void)
{
NODE_T n1;
NODE_T n2;
NODE_T n3;
NODE_T n4;
NODE_T n5;
NODE_T n6;
debug_set_level ( DBG_LEVEL_ALL );
DEBUG_INFO(" test start!\n");
delay_ms(10);
n1.data = 5;
n2.data = 6;
n3.data = 7;
n4.data = 8;
n5.data = 9;
n6.data = 10;
n1.left = &n2;
n1.right = &n3;
n2.left = &n4;
n2.right = &n5;
n3.left = &n6;
n3.right = NULL;
n4.left = NULL;
n4.right = NULL;
n5.left = NULL;
n5.right = NULL;
n6.left = NULL;
n6.right = NULL;
DEBUG_INFO("preorder test !\n");delay_ms(10);
preorder(&n1); // 5 6 8 9 7 10
printf("\n");
DEBUG_INFO("inorder test !\n");delay_ms(10);
inorder(&n1); // 8 6 9 5 10 7
printf("\n");
DEBUG_INFO("postorder test !\n");delay_ms(10);
postorder(&n1); // 8 9 6 10 7 5
printf("\n");
DEBUG_INFO(" end!\n");
while(1)
{
}
}
测试数据
测试结果:
[INFO][bsp_test.c #396][@test_tree]: test start!
[INFO][bsp_test.c #422][@test_tree]:preorder test !
5 6 8 9 7 10
[INFO][bsp_test.c #425][@test_tree]:inorder test !
8 6 9 5 10 7
[INFO][bsp_test.c #428][@test_tree]:postorder test !
8 9 6 10 7 5
[INFO][bsp_test.c #431][@test_tree]: end!
By Urien 2021/11/7