树四:遍历二叉树

二叉树遍历:

  从根结点开始,按照某种次序依次访问二叉树中的所有结点。

前序遍历:

  

中序遍历:

后序遍历:

层次遍历:

  

代码实现:

/* main.c */
#include <stdio.h>
#include <stdlib.h>
#include "BTree.h"
#include "LinkQueue.h"

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

struct Node
{
    BTreeNode header;
    char v;
};

void printf_data(BTreeNode* node)
{
    if( node != NULL )
    {
        printf("%c", ((struct Node*)node)->v);
    }
}

void pre_order_traversal(BTreeNode* root)
{
    if( root != NULL )
    {
        printf("%c, ", ((struct Node*)root)->v);

        pre_order_traversal(root->left);
        pre_order_traversal(root->right);
    }
}

void middle_order_traversal(BTreeNode* root)
{
    if( root != NULL )
    {
        middle_order_traversal(root->left);

        printf("%c, ", ((struct Node*)root)->v);

        middle_order_traversal(root->right);
    }
}

void post_order_traversal(BTreeNode* root)
{
    if( root != NULL )
    {
        post_order_traversal(root->left);

        post_order_traversal(root->right);

        printf("%c, ", ((struct Node*)root)->v);
    }
}

void level_order_traversal(BTreeNode* root)
{
    if( root != NULL )
    {
       LinkQueue* queue = LinkQueue_Create();

       if( queue != NULL )
       {
            LinkQueue_Append(queue, root);

            while( LinkQueue_Length(queue) > 0 )
            {
                struct Node* node = (struct Node*)LinkQueue_Retrieve(queue);

                printf("%c, ", node->v);

                LinkQueue_Append(queue, node->header.left);
                LinkQueue_Append(queue, node->header.right);
            }
       }

       LinkQueue_Destroy(queue);
    }
}

int main(int argc, char *argv[])
{
    BTree* tree = BTree_Create();

    struct Node n1 = {{NULL, NULL}, ‘A‘};
    struct Node n2 = {{NULL, NULL}, ‘B‘};
    struct Node n3 = {{NULL, NULL}, ‘C‘};
    struct Node n4 = {{NULL, NULL}, ‘D‘};
    struct Node n5 = {{NULL, NULL}, ‘E‘};
    struct Node n6 = {{NULL, NULL}, ‘F‘};

    BTree_Insert(tree, (BTreeNode*)&n1, 0, 0, 0);
    BTree_Insert(tree, (BTreeNode*)&n2, 0x00, 1, 0);
    BTree_Insert(tree, (BTreeNode*)&n3, 0x01, 1, 0);
    BTree_Insert(tree, (BTreeNode*)&n4, 0x00, 2, 0);
    BTree_Insert(tree, (BTreeNode*)&n5, 0x02, 2, 0);
    BTree_Insert(tree, (BTreeNode*)&n6, 0x02, 3, 0);

    printf("Full Tree: \n");

    BTree_Display(tree, printf_data, 4, ‘-‘);

    printf("Pre Order Traversal:\n");

    pre_order_traversal(BTree_Root(tree));

    printf("\n");

    printf("Middle Order Traversal:\n");

    middle_order_traversal(BTree_Root(tree));

    printf("\n");

    printf("Post Order Traversal:\n");

    post_order_traversal(BTree_Root(tree));

    printf("\n");

    printf("Level Order Traversal:\n");

    level_order_traversal(BTree_Root(tree));

    printf("\n");

    BTree_Destroy(tree);

    return 0;
}
/* LinkQueue.h */
#ifndef _LINKQUEUE_H_
#define _LINKQUEUE_H_

typedef void LinkQueue;

LinkQueue* LinkQueue_Create();

void LinkQueue_Destroy(LinkQueue* queue);

void LinkQueue_Clear(LinkQueue* queue);

int LinkQueue_Append(LinkQueue* queue, void* item);

void* LinkQueue_Retrieve(LinkQueue* queue);

void* LinkQueue_Header(LinkQueue* queue);

int LinkQueue_Length(LinkQueue* queue);

#endif
/*LinkQueue.c */
#include <malloc.h>
#include <stdio.h>
#include "LinkQueue.h"

typedef struct _tag_LinkQueueNode TLinkQueueNode;
struct _tag_LinkQueueNode
{
    TLinkQueueNode* next;
    void* item;
};

typedef struct _tag_LinkQueue
{
    TLinkQueueNode* front;
    TLinkQueueNode* rear;
    int length;
} TLinkQueue;

LinkQueue* LinkQueue_Create() // O(1)
{
    TLinkQueue* ret = (TLinkQueue*)malloc(sizeof(TLinkQueue));

    if( ret != NULL )
    {
        ret->front = NULL;
        ret->rear = NULL;
        ret->length = 0;
    }

    return ret;
}

void LinkQueue_Destroy(LinkQueue* queue) // O(n)
{
    LinkQueue_Clear(queue);
    free(queue);
}

void LinkQueue_Clear(LinkQueue* queue) // O(n)
{
    while( LinkQueue_Length(queue) > 0 )
    {
        LinkQueue_Retrieve(queue);
    }
}

int LinkQueue_Append(LinkQueue* queue, void* item) // O(1)
{
    TLinkQueue* sQueue = (TLinkQueue*)queue;
    TLinkQueueNode* node = (TLinkQueueNode*)malloc(sizeof(TLinkQueueNode));
    int ret = (sQueue != NULL ) && (item != NULL) && (node != NULL);

    if( ret )
    {
        node->item = item;

        if( sQueue->length > 0 )
        {
            sQueue->rear->next = node;
            sQueue->rear = node;
            node->next = NULL;
        }
        else
        {
            sQueue->front = node;
            sQueue->rear = node;
            node->next = NULL;
        }

        sQueue->length++;
    }

    if( !ret )
    {
        free(node);
    }

    return ret;
}

void* LinkQueue_Retrieve(LinkQueue* queue) // O(1)
{
    TLinkQueue* sQueue = (TLinkQueue*)queue;
    TLinkQueueNode* node = NULL;
    void* ret = NULL;

    if( (sQueue != NULL) && (sQueue->length > 0) )
    {
        node = sQueue->front;

        sQueue->front = node->next;

        ret = node->item;

        free(node);

        sQueue->length--;

        if( sQueue->length == 0 )
        {
            sQueue->front = NULL;
            sQueue->rear = NULL;
        }
    }

    return ret;
}

void* LinkQueue_Header(LinkQueue* queue) // O(1)
{
    TLinkQueue* sQueue = (TLinkQueue*)queue;
    void* ret = NULL;

    if( (sQueue != NULL) && (sQueue->length > 0) )
    {
        ret = sQueue->front->item;
    }

    return ret;
}

int LinkQueue_Length(LinkQueue* queue) // O(1)
{
    TLinkQueue* sQueue = (TLinkQueue*)queue;
    int ret = -1;

    if( sQueue != NULL )
    {
        ret = sQueue->length;
    }

    return ret;
}
/* BTree.h */
#ifndef _BTREE_H_
#define _BTREE_H_

#define BT_LEFT 0
#define BT_RIGHT 1

typedef void BTree;
typedef unsigned long long BTPos;

typedef struct _tag_BTreeNode BTreeNode;
struct _tag_BTreeNode
{
    BTreeNode* left;
    BTreeNode* right;
};

typedef void (BTree_Printf)(BTreeNode*);

BTree* BTree_Create();

void BTree_Destroy(BTree* tree);

void BTree_Clear(BTree* tree);

int BTree_Insert(BTree* tree, BTreeNode* node, BTPos pos, int count, int flag);

BTreeNode* BTree_Delete(BTree* tree, BTPos pos, int count);

BTreeNode* BTree_Get(BTree* tree, BTPos pos, int count);

BTreeNode* BTree_Root(BTree* tree);

int BTree_Height(BTree* tree);

int BTree_Count(BTree* tree);

int BTree_Degree(BTree* tree);

void BTree_Display(BTree* tree, BTree_Printf* pFunc, int gap, char div);

#endif
/* BTree.c */
#include <stdio.h>
#include <malloc.h>
#include "BTree.h"

typedef struct _tag_BTree TBTree;
struct _tag_BTree
{
    int count;
    BTreeNode* root;
};

static void recursive_display(BTreeNode* node, BTree_Printf* pFunc, int format, int gap, char div) // O(n)
{
    int i = 0;

    if( (node != NULL) && (pFunc != NULL) )
    {
        for(i=0; i<format; i++)
        {
            printf("%c", div);
        }

        pFunc(node);

        printf("\n");

        if( (node->left != NULL) || (node->right != NULL) )
        {
            recursive_display(node->left, pFunc, format + gap, gap, div);
            recursive_display(node->right, pFunc, format + gap, gap, div);
        }
    }
    else
    {
        for(i=0; i<format; i++)
        {
            printf("%c", div);
        }
        printf("\n");
    }
}

static int recursive_count(BTreeNode* root) // O(n)
{
    int ret = 0;

    if( root != NULL )
    {
        ret = recursive_count(root->left) + 1 + recursive_count(root->right);
    }

    return ret;
}

static int recursive_height(BTreeNode* root) // O(n)
{
    int ret = 0;

    if( root != NULL )
    {
        int lh = recursive_height(root->left);
        int rh = recursive_height(root->right);

        ret = ((lh > rh) ? lh : rh) + 1;
    }

    return ret;
}

static int recursive_degree(BTreeNode* root) // O(n)
{
    int ret = 0;

    if( root != NULL )
    {
        if( root->left != NULL )
        {
            ret++;
        }

        if( root->right != NULL )
        {
            ret++;
        }

        if( ret == 1 )
        {
            int ld = recursive_degree(root->left);
            int rd = recursive_degree(root->right);

            if( ret < ld )
            {
                ret = ld;
            }

            if( ret < rd )
            {
                ret = rd;
            }
        }
    }

    return ret;
}

BTree* BTree_Create() // O(1)
{
    TBTree* ret = (TBTree*)malloc(sizeof(TBTree));

    if( ret != NULL )
    {
        ret->count = 0;
        ret->root = NULL;
    }

    return ret;
}

void BTree_Destroy(BTree* tree) // O(1)
{
    free(tree);
}

void BTree_Clear(BTree* tree) // O(1)
{
    TBTree* btree = (TBTree*)tree;

    if( btree != NULL )
    {
        btree->count = 0;
        btree->root = NULL;
    }
}

int BTree_Insert(BTree* tree, BTreeNode* node, BTPos pos, int count, int flag) // O(n)
{
    TBTree* btree = (TBTree*)tree;
    int ret = (btree != NULL) && (node != NULL) && ((flag == BT_LEFT) || (flag == BT_RIGHT));
    int bit = 0;

    if( ret )
    {
        BTreeNode* parent = NULL;
        BTreeNode* current = btree->root;

        node->left = NULL;
        node->right = NULL;

        while( (count > 0) && (current != NULL) )
        {
            bit = pos & 1;
            pos = pos >> 1;

            parent = current;

            if( bit == BT_LEFT )
            {
                current = current->left;
            }
            else if( bit == BT_RIGHT )
            {
                current = current->right;
            }

            count--;
        }

        if( flag == BT_LEFT )
        {
            node->left = current;
        }
        else if( flag == BT_RIGHT )
        {
            node->right = current;
        }

        if( parent != NULL )
        {
            if( bit == BT_LEFT )
            {
                parent->left = node;
            }
            else if( bit == BT_RIGHT )
            {
                parent->right = node;
            }
        }
        else
        {
            btree->root = node;
        }

        btree->count++;
    }

    return ret;
}

BTreeNode* BTree_Delete(BTree* tree, BTPos pos, int count) // O(n)
{
    TBTree* btree = (TBTree*)tree;
    BTreeNode* ret = NULL;
    int bit = 0;

    if( btree != NULL )
    {
        BTreeNode* parent = NULL;
        BTreeNode* current = btree->root;

        while( (count > 0) && (current != NULL) )
        {
            bit = pos & 1;
            pos = pos >> 1;

            parent = current;

            if( bit == BT_LEFT )
            {
                current = current->left;
            }
            else if( bit == BT_RIGHT )
            {
                current = current->right;
            }

            count--;
        }

        if( parent != NULL )
        {
            if( bit == BT_LEFT )
            {
                parent->left = NULL;
            }
            else if( bit == BT_RIGHT )
            {
                parent->right = NULL;
            }
        }
        else
        {
            btree->root = NULL;
        }

        ret = current;

        btree->count = btree->count - recursive_count(ret);
    }

    return ret;
}

BTreeNode* BTree_Get(BTree* tree, BTPos pos, int count) // O(n)
{
    TBTree* btree = (TBTree*)tree;
    BTreeNode* ret = NULL;
    int bit = 0;

    if( btree != NULL )
    {
        BTreeNode* current = btree->root;

        while( (count > 0) && (current != NULL) )
        {
            bit = pos & 1;
            pos = pos >> 1;

            if( bit == BT_LEFT )
            {
                current = current->left;
            }
            else if( bit == BT_RIGHT )
            {
                current = current->right;
            }

            count--;
        }

        ret = current;
    }

    return ret;
}

BTreeNode* BTree_Root(BTree* tree) // O(1)
{
    TBTree* btree = (TBTree*)tree;
    BTreeNode* ret = NULL;

    if( btree != NULL )
    {
        ret = btree->root;
    }

    return ret;
}

int BTree_Height(BTree* tree) // O(n)
{
    TBTree* btree = (TBTree*)tree;
    int ret = 0;

    if( btree != NULL )
    {
        ret = recursive_height(btree->root);
    }

    return ret;
}

int BTree_Count(BTree* tree) // O(1)
{
    TBTree* btree = (TBTree*)tree;
    int ret = 0;

    if( btree != NULL )
    {
        ret = btree->count;
    }

    return ret;
}

int BTree_Degree(BTree* tree) // O(n)
{
    TBTree* btree = (TBTree*)tree;
    int ret = 0;

    if( btree != NULL )
    {
        ret = recursive_degree(btree->root);
    }

    return ret;
}

void BTree_Display(BTree* tree, BTree_Printf* pFunc, int gap, char div) // O(n)
{
    TBTree* btree = (TBTree*)tree;

    if( btree != NULL )
    {
        recursive_display(btree->root, pFunc, 0, gap, div);
    }
}
时间: 2024-11-10 01:12:24

树四:遍历二叉树的相关文章

【树4】二叉树的遍历

简介 遍历二叉树就是按照某种顺序,将树中的结点都枚举一遍,且每个结点仅仅访问一次.因为树不是线性的结构,遍历不像线性表那样简单,因此他的遍历需要特点的算法来完成. 从某种角度讲,对二叉树的遍历就是将树形结构转换为线性结构的操作. 二叉树的遍历方法主要有如下几种: 先序遍历:先访问root结点,再先序遍历左子树,再先序遍历右子树. 中序遍历:先中序遍历左子树,再访问root结点,再中序遍历右子树. 后序遍历:先后序遍历左子树,再后序遍历右子树,再访问root结点. 层遍历:从上到下,从左到右,一层

javascript实现数据结构: 树和二叉树的应用--最优二叉树(赫夫曼树),回溯法与树的遍历--求集合幂集及八皇后问题

赫夫曼树及其应用 赫夫曼(Huffman)树又称最优树,是一类带权路径长度最短的树,有着广泛的应用. 最优二叉树(Huffman树) 1 基本概念 ① 结点路径:从树中一个结点到另一个结点的之间的分支构成这两个结点之间的路径. ② 路径长度:结点路径上的分支数目称为路径长度. ③ 树的路径长度:从树根到每一个结点的路径长度之和. 以下图为例: A到F :结点路径 AEF : 路径长度(即边的数目) 2 : 树的路径长度:3*1+5*2+2*3=19: ④ 结点的带权路径长度:从该结点的到树的根结

团体程序设计天梯赛 L2-006. 树的遍历 L2-011. 玩转二叉树

L2-006. 树的遍历 1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <stdbool.h> 5 6 struct node 7 { 8 long left,right; 9 }tree[10000]; 10 11 long a[31],b[31]; 12 13 void work(long l,long r,long p,long q,long fa

树的遍历 (和) 玩转二叉树 的总结博客

树的遍历: 关键在与如何利用中序和后序建树. 中序的作用,提供了左右子树的所有节点的分布! 前序,后序的作用:就是第一个元素(最后一个元素)提供了根节点,让中序找到子树的分布情况. #include<iostream> #include<queue> #include<vector> using namespace std; const int maxn = 100; int af[maxn], in[maxn], n; struct node{ int l, r; }

数据结构 第5章 树的二叉树 单元小结(2)遍历二叉树和线索二叉树

概念: 遍历二叉树: 遍历:指按某条搜索路线遍访每个结点且不重复(又称周游). 遍历的用途:它是树结构插入.删除.修改.查找和排序运算的前提,是二叉树一切运算的基础和核心. 时间效率: O(n) //每个结点最多访问两次 空间效率: O(n) //栈占用的最大辅助空间 用栈进行迭代运算 和队列很像 先序: 中序: void PreOrderlteration(BiTree T) void InOrderIteration(BiTree T) { stack<BiTree> s; stack&l

数据结构学习笔记(四)---遍历二叉树

遍历二叉树   二叉树是一种非线性的数据结构.所谓的遍历二叉树就是按某种顺序访问二叉树中的每个节点,要求每个节点被访问一次且仅一次. 遍历操作实际上是将非线性结构线性化过程,其结果为线性序列.   二叉树的操作 (1)先序遍历---结束的条件是二叉树是否为空 TLR 先访问根节点: 再先序访问左子树: 再先序访问右子树. (2)中序遍历---结束的条件是二叉树是否为空  LTR 先中序遍历左子树: 再访问根节点: 再中序遍历右子树. (3)后序遍历---结束的条件是二叉树是否为空  LRT 先后

数据结构算法C语言实现(二十)--- 6.3.1遍历二叉树

一.简述 二叉树的遍历主要是先序.中序.后序及对应的递归和非递归算法,共3x2=6种,其中后序非递归在实现上稍复杂一些.二叉树的遍历是理解和学习递归及体会栈的工作原理的绝佳工具! 此外,非递归所用的栈及相关操作是第三章实现的,但数据类型做了更改. 二.头文件 1 //3_1.h 2 /** 3 author:zhaoyu 4 email:[email protected] 5 date:2016-6-7 6 note:realize my textbook <<数据结构(C语言版)>&g

12.遍历二叉树与二叉树的建立

一.遍历二叉树 1.定义 二叉树的遍历(travering binary tree)是指从根结点出发,按照某种次序依次访问二叉树中的所有结点,使得每个结点被访问一次且仅被访问一次. 2.前序遍历 (1)规则:若二叉树为空,则空操作返回.否则,先访问根结点,然后前序遍历左子树,再前序遍历右子树. (2)实例 前序遍历结果为:A BDGH CEIF 分析:当最先访问根结点后,然后前序遍历左子树.当访问根的左子树时,这里"前序遍历"即我们将B假设为左子树的根来遍历. (3)算法 从二叉树定义

二叉树 二叉树的性质 存储结构 遍历二叉树 C实现二叉树的创建和遍历 线索二叉树

定义 二叉树(binary tree)是n(n>=0)个结点的有限集合,该集合为空集合称为空二叉树,或者有一个根结点和两棵互不相交的,分别称为树根结点的左孩子树和右孩子树组成. 二叉树的特点 每个结点最多有两棵子树,所以二叉树总没有度大于2的结点 左子树和右子树是有顺序的,次数不能任意颠倒 即使树中某结点只有一棵子树,也要区分是左子树还是右子树 特殊的二叉树 1. 斜树 所有的结点都只有左子树的二叉树称为左斜树; 所有的结点都只有右子树的二叉树称为右斜树; 这两者统称为斜树 2. 满二叉树 在一

树的遍历与图的遍历

研发时候,不要受原来的术语的影响,其实就是想着原来学过的或者看过的可以解决新遇到的问题,这其实是侥幸心理,忘记原来的术语吧,那只是你创新的源泉. 遍历就是把节点按一定规则构成一个线性序列,不同的规则得到不同顺序的线性序列,仅此而已 . 算法是实际问题工作步骤的抽象,不要一味想算法,想想实际情况怎么做的,然后提取算法,然后优化. 不论怎样,要和具体的数据结构结合在一起. 一.树的遍历 对于树的遍历,有三种,就拿前序遍历来说,得到的序列不论怎么拆分(子串,就是要连续),始 终要是根左右,跟在左右前面