二叉树三种遍历方式的非递归写法/构建二叉树

1 参考链接 这里

2 利用原二叉树的扩展二叉树的前序遍历序列构建二叉树,并对该二叉树进行中序遍历(非递归)

#include <cstdio>
#include <stack>
#include <iostream>
using namespace std;

//树节点表示
typedef struct BiTNode
{
    int value;
    struct BiTNode *lchild,*rchild;
}BiTNode ,*BiTree;

//中序遍历的非递归写法
void inorder_circle(BiTree root)
{
    if(root==NULL)
        return;
    BiTree node=root;
    stack<BiTree> s;
    while(!s.empty()||node)
    {
        while(node)
        {
            s.push(node);
            node=node->lchild;
        }

        if(!s.empty())
        {
            node=s.top();
            s.pop();
            printf("%c",node->value);
            node=node->rchild;
        }
    }
    printf("\n");
}

//前序遍历构建二叉树
void PreCreateTree(BiTree *T)
{
    char ch;
    scanf("%c",&ch);
    if(ch=='#')
        *T=NULL;
    else
    {
        *T=new BiTNode;
        (*T)->value=ch;
        PreCreateTree(&(*T)->lchild);
        PreCreateTree(&(*T)->rchild);

    }
}

int main()
{
    BiTree p;

    printf("前序遍历构建二叉树\n");
    PreCreateTree(&p);
    printf("中序遍历输出二叉树\n");
    inorder_circle(p);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40123329/article/details/86366319