二叉树的遍历

来源:互联网 发布:中国东南亚战略知乎 编辑:程序博客网 时间:2024/06/06 02:49
二叉树的存储方式
最好用链式存储结构来存储,每个结点一个数据域两个指针域。指针域一个指向左儿子一个指向右儿子。
其中完全二叉树用顺序存储方式比较好,具体看堆
二叉树的遍历
先序----根、左子树、右子树;
中序----左子树、根、右子树;
后序----左子树、右子树、根
层次遍历----从上到下、从左到右
先序中序后序这三种均是用一种递归的方式实现,代码很简单。如果不用递归还可以借助堆栈的方式去做。下图就是先序中序后序遍历的效果。
先序、中序和后序遍历过程:遍历过程中经过结点的路线一样,只是访问各结点的时机不同

层序遍历使用了队列!
二叉树的遍历程序
typedef struct TNode *Position;typedef Position BinTree; /* 二叉树类型 */struct TNode{ /* 树结点定义 */    ElementType Data; /* 结点数据 */    BinTree Left;     /* 指向左子树 */    BinTree Right;    /* 指向右子树 */};void InorderTraversal( BinTree BT ){    if( BT ) {        InorderTraversal( BT->Left );        /* 此处假设对BT结点的访问就是打印数据 */        printf("%d ", BT->Data); /* 假设数据为整型 */        InorderTraversal( BT->Right );    }} void PreorderTraversal( BinTree BT ){    if( BT ) {        printf("%d ", BT->Data );        PreorderTraversal( BT->Left );        PreorderTraversal( BT->Right );    }} void PostorderTraversal( BinTree BT ){    if( BT ) {        PostorderTraversal( BT->Left );        PostorderTraversal( BT->Right );        printf("%d ", BT->Data);    }} void LevelorderTraversal ( BinTree BT ){     Queue Q;     BinTree T;     if ( !BT ) return; /* 若是空树则直接返回 */         Q = CreatQueue(); /* 创建空队列Q */    AddQ( Q, BT );    while ( !IsEmpty(Q) ) {        T = DeleteQ( Q );        printf("%d ", T->Data); /* 访问取出队列的结点 */        if ( T->Left )   AddQ( Q, T->Left );        if ( T->Right )  AddQ( Q, T->Right );    }}




原创粉丝点击