二叉树

来源:互联网 发布:python 给字典赋值 编辑:程序博客网 时间:2024/05/21 04:25

一、二叉树的结构

typedef struct tree{    char date;    tree *lchil;    tree *rchil;}tree;

这里写图片描述

二、二叉树的创建

void create_tree(tree **root){//if (root != NULL)    {        char put = ' ';        scanf("%c", &put);        if (put == '.')            *root = NULL;        else        {            *root = (tree*)malloc(sizeof(tree));            (*root)->date = put;            create_tree(&((*root)->lchil));            create_tree(&((*root)->rchil));        }    }}

核心思想:创建一个节点,再创建它的左孩子,右孩子。一直循环这个过程,所以创建的时候使用递归。

三、二叉树的先序遍历(递归实现)

void pre(tree *root){    if (root != NULL)    {        printf("%c*",root->date);        pre(root->lchil);        pre(root->rchil);    }}

先序遍历:先遍历根节点,再遍历左孩子,再遍历右孩子。
根据概念写出递归遍历过程。

四、二叉树的中序遍历(递归实现)

void in(tree *root){    if (root != NULL)    {        in(root->lchil);        printf("%c*", root->date);        in(root->rchil);    }}

中序遍历:先遍历左孩子,再遍历根节点,最后遍历右孩子。
根据概念写出递归的遍历过程。

五、二叉树的后序遍历(递归实现)

void before(tree *root){    if (root != NULL)    {        before(root->lchil);        before(root->rchil);        printf("%c*", root->date);    }}

后序遍历:先遍历左孩子,再遍历右孩子,最后遍历根节点。
根据概念写出遍历过程。

六、二叉树先序遍历(非递归实现)

void pre1(tree *root){    stack<tree*> tr;    tree *p = root;    while(p!=NULL||!tr.empty())    if (p != NULL)    {        printf("%c",p->date);        tr.push(p);        p=p->lchil;    }    else    {        p = tr.top();        tr.pop();        p = p->rchil;    }}

这里写图片描述

七、二叉树的中序遍历(非递归实现)

中序遍历类似于先序遍历

void in1(tree *root){    stack<tree*> tr;    tree *p = root;    while (p != NULL || !tr.empty())        if (p != NULL)        {            tr.push(p);            p = p->lchil;        }        else        {            p = tr.top();            printf("%c", p->date);            tr.pop();            p = p->rchil;        }}

八、二叉树的后序遍历(非递归实现)

void before1(tree *root){    stack<tree*> tr;    tree *p = root;    tree *q = root;    while (p != NULL || !tr.empty())    {        while (p != NULL)        {            tr.push(p);            p = p->lchil;        }        if(!tr.empty())        {            p = tr.top();            if (p->rchil == NULL||p->rchil==q)            {                printf("%c",p->date);                q = p;                tr.pop();                p = NULL;            }            else                p = p->rchil;        }    }}

这里写图片描述