不用堆栈实现树的先序遍历

通常实现树的先序遍历时,我们都需要一个栈来记录位置信息,如果一颗二叉树当中本来就保存了指向父亲的节点,那么我们可以不用堆栈来实现先序遍历。

#include<iostream>
using namespace std;
class node
{
public:
    char value;
    node *parent,*left,*right;
    node(char v):parent(0),left(0),right(0)
    {
        value=v;
    }
};
void first(node *r)
{
    if(r!=NULL)
    {
        cout<<r->value<<endl;
        first(r->left);
        first(r->right);
    }
}
void fun(node *r)
{
    node *p=r;
    node *q;
    bool xunhuan=true;
    
    while(xunhuan)
    {
        if(p)
        {
            cout<<p->value<<endl;
            if(p->left!=NULL)// 往左走
            {
                p=p->left;
            }
            else
            {
                if(p->right!=NULL)
                {
                    p=p->right;
                }
                else 
                {
                    bool flag=true;
                    while(true)
                    {
                        while(p->parent!=NULL&&p->parent->right==p)
                            p=p->parent;
                        if(p->parent==NULL)
                        {
                            xunhuan=false;
                            break;
                        }

                        p=p->parent;
                        while(p->parent==NULL||p==p->parent->left)
                        {
                            if(p->right!=NULL)
                            {
                                p=p->right;
                                flag=false;
                                break;
                            }
                        }
                        if(!flag)
                        {
                            flag=true;
                            break;
                        }
                        if(p->parent==NULL)
                        {
                            xunhuan=false;
                            break;
                        }
                        
                    }

                }
            }
        }
    }
}
void main()
{
    node A('A'),B('B'),C('C'),D('D'),E('E'),F('F');
    A.left=&B;
    A.right=&C;
    B.parent=&A;
    C.parent=&A;
    B.left=&D;
    B.right=&E;
    D.parent=&B;
    E.parent=&B;
    C.left=&F;
    F.parent=&C;
    first(&A);
    cout<<"循环遍历"<<endl;
    fun(&A);

    system("pause");

}

以上代码可以直接运行。

原文地址:https://www.cnblogs.com/dyc0113/p/4780490.html