二叉树的构造,递归遍历,非递归遍历

来源:互联网 发布:怎么申请不了淘宝直播 编辑:程序博客网 时间:2024/05/19 16:38

二叉树的非递归遍历在面试的时候也会问到,好像后续的非递归遍历比较麻烦,我没有进一步了解,只实现了前序和中序的非递归遍历。
前序:根节点,左孩子,右孩子;
中序:左孩子,根节点,右孩子;
后序:左孩子,右孩子,根节点;

#include <iostream>#include <stack>#include <iostream>using namespace std;struct BinaryTree{    int data;    BinaryTree* left;    BinaryTree *right;};//中序方式递归遍历二叉树void InOrder(BinaryTree *root){    if (root!=NULL)    {        InOrder(root->left);        cout<<root->data<<" ";        InOrder(root->right);    }    //cout<<endl;}//中序方式非递归遍历二叉树void IterInOrderBinaryTree(BinaryTree *root){    BinaryTree *p=root;    stack<BinaryTree *> S;    while(p||!S.empty())    {        while(p)        {            S.push(p);            p=p->left;        }        if (!S.empty())        {            p=S.top();            S.pop();            cout<<p->data<<" ";            p=p->right;        }    }    cout<<endl;}//前序遍历二叉树,递归void Pre(BinaryTree *root){    if (root!=NULL)    {        cout<<root->data<<" ";        Pre(root->left);        Pre(root->right);    }    //cout<<endl;}//前序1遍历二叉树,非递归void PreIter(BinaryTree *root){    stack<BinaryTree *>S;    BinaryTree *p=root;    while(p||!S.empty())    {        while(p!=NULL)        {            cout<<p->data<<" ";            S.push(p);            p=p->left;        }        if (!S.empty())        {            p=S.top();            S.pop();            p=p->right;        }    }    cout<<endl;}//以先序方式构造二叉树void ConstructBinaryTree(BinaryTree **root){    int n;    cin>>n;    if (n<0)    {        *root=NULL;    }    else    {        *root=(BinaryTree*)malloc(sizeof(BinaryTree));        (*root)->data=n;        ConstructBinaryTree(&(*root)->left);        ConstructBinaryTree(&(*root)->right);    }}int main(){    BinaryTree *root=NULL;    ConstructBinaryTree(&root);    cout<<"递归前序遍历:";    Pre(root);    cout<<endl;    cout<<"非递归前序遍历:";    PreIter(root);    cout<<"递归中序遍历:";    InOrder(root);    cout<<endl;    cout<<"非递归中序遍历:";    IterInOrderBinaryTree(root);    return 0;}
1 0
原创粉丝点击