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

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

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值