二叉树的创建和前中后三种遍历方法

来源:互联网 发布:淘宝卖家快捷回复短语 编辑:程序博客网 时间:2024/05/19 17:51

头文件:

#include<stdlib.h>#include<stdio.h>typedef struct bnode{    int data;//结点数据类型    struct bnode *lchild, *rchild;// 定义左右孩子为指针类型}btree;btree *insert_node(btree *root, int node) //插入结点的函数{    btree *newpointer;    btree *currentpointer;    btree *parentpointer;    newpointer = (btree *)malloc(sizeof(btree));//向系统申请内存的函数malloc    newpointer->data=node;    newpointer->lchild=NULL;    newpointer->rchild=NULL;    if(root==NULL)        return newpointer;    else    {        currentpointer=root;        while(currentpointer!=NULL)        {            parentpointer=currentpointer;            //若当前插入的值比父结点小,放在左,否则放在右            if(currentpointer->data>node)                currentpointer=currentpointer->lchild;            else                currentpointer=currentpointer->rchild;        }        if(parentpointer->data>node)            parentpointer->lchild=newpointer;        else            parentpointer->rchild=newpointer;    }    return root;}btree *create_btree(int data[], int len) //建立二叉树{    int i;    btree *root = NULL;    for(i=0; i<len; i++)    {        root=insert_node(root,data[i]);//调用插入二叉树结点的函数    }    return root;}

二叉树的前序非递归遍历:

//前序遍历,从根节点开始,再到左子树 再到右子树void preorder(btree *root){    btree *p, *s[100];    int top=0;    p=root;    while((p!=NULL)||(top>0))    {        while(p!=NULL)        {            printf("%d",p->data);//直接输出根节点,然后左然后右            s[++top]=p;            p=p->lchild;        }        p=s[top--];        p=p->rchild;    }}int main(){    btree *root=NULL;    int value, index, nodelist[20];    index=0;    scanf("%d", &value);    while(value!=0)    {        nodelist[index]=value;        index++;        scanf("%d",&value);    }    root= create_btree(nodelist,index);    preorder(root);    return 0;}


二叉树的中序递归遍历:先遍历左子树,再根结点,再右子树

<pre name="code" class="csharp">void inorder(btree *root){    if(root!=NULL)    {        inorder(root->lchild);// left child        printf("%d",root->data); // root        inorder(root->rchild);// right child    }}int main(){    btree *root=NULL;    int value, index, nodelist[100];    index=0;    scanf("%d",&value);    while(value!=0)    {        nodelist[index]=value;        index++;        scanf("%d",&value);    }    root=create_btree(nodelist,index);    inorder(root);    return 0;}


二叉树的后序递归遍历: 先左子树,再右子树,再根节点

void postorder(btree *root){    if(root!=NULL)    {        postorder(root->lchild);// left         postorder(root->rchild);// right        printf("%d",root->data); // root    }}int main(){    btree *root = NULL;    int value,index,nodelist[100];    index=0;    scanf("%d",&value);    while(value!=0)    {        nodelist[index]=value;        index++;        scanf("%d",&value);    }    root=create_btree(nodelist,index);    postorder(root);}



0 0