二叉树的几种遍历以及给两种求另外一种

1.  二叉树 定义结点类型

typedef struct node
{
    int data;
    struct node* lchild;
    struct node* rchild;
} Tnode;

2.  二叉树的先序遍历:根节点——左子树——右字树

   递归遍历:

void PreOrder(Tnode*  root)
{
    if(root==NULL)
        return ;
    cout<<root->val<<endl;
    Preorder(root->lchild);
    Preorder(root->rchild);
}

   非递归遍历:

void PreOrder(Tnode *root)
{
    if(root==NULL)
        return ;
    stack<Tnode *>s;
    Tnode *now=root;
    while(!s.empty() || now)
    {
        while(now)
        {
            cout<<now->val<<"->";
            s.push(now);
            now=now->lchild;
        }
        now=s.top();
        s.pop();
        now=now->rchild;  
    }
    cout<<endl;
}

3.  二叉树的中序遍历:左子树——根节点——右字树

   递归遍历:

void InOrder(Tnode*  root)
{
    if(root==NULL)
        return ;
    Preorder(root->lchild);
    cout<<root->val<<endl;
    Preorder(root->rchild);
}

   非递归遍历:

void InOrder(Tnode *root)
{
    if(root==NULL)
        return ;
    stack<Tnode *>s;
    Tnode *now=root;
    while(!s.empty() || now)
    {
        while(now)
        {
            s.push(now);
            now=now->lchild;
        }
        now=s.top();
        cout<<now->val<<"->";
        s.pop();
        now=now->rchild;  
    }
    cout<<endl;
}

4.  后序遍历:左子树——右字树——根节点

   递归遍历:

void PostOrder(Tnode*  root)
{
    if(root==NULL)
        return ;
    Preorder(root->lchild);
    Preorder(root->rchild);
    cout<<root->val<<endl;
}

   非递归遍历:

void PostOrder(Tnode *root)
{
    if(root==NULL)
        return ;
    stack<Tnode *>s;
    Tnode *now=root;
    Tnode *last=NULL;
    while(!s.empty() || now)
    {
        while(now)
        {
            s.push(now);
            now=now->lchild;
        }
        now=s.top();
        if(now->rchild && last!=now->rchild)
            now=now->rchild;
        else if(now->rchild ==NULL || last ==now->rchild)
        {
            cout<<<now->val<<"->";
            last=now;
            s.pop();
            now=NULL;
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/jkzr/p/10594783.html