非递归遍历二叉树

void preTraval(Node *head) {
	if (head == NULL)
		return;

	stack<Node *> st;
	st.push(head);

	while (!st.empty() ) {
		Node *t = st.top();
		st.pop();

		while (t) {//一边顺着左路走,一边遍历,并把右孩子放入栈中
			visit(t);
			if (t->right)
				st.push(t->right);
			t = t->left;
		}
	}
}

void inTraval(Node *head) {
	if (head == NULL)
		return;
	Node * t = head;
	stack<Node *> st;
	while (t !=NULL || !st.empty()) {
		while (t != NULL) {//顺着左路走,并把节点放入栈中
			st.push(t);
			t = t->left;
		}

		if (!st.empty()) {//走到左路的头之后,取栈中的节点,向右拐
			t = st.top();
			st.pop();
			visit(t);
			t = t->right;
		}
	}
	
}


后序比较复杂

#define maxsize 100
typedef enum{L,R} tagtype;
typedef struct 
{
    Bitree ptr;
    tagtype tag;
}stacknode;

typedef struct
{
    stacknode Elem[maxsize];
    int top;
}SqStack;

void PostOrderUnrec(Bitree t)
{
    SqStack s;
    stacknode x;
    StackInit(s);
    p=t;
    
    do 
    {
        while (p!=null)        //遍历左子树
        {
            x.ptr = p; 
            x.tag = L;         //标记为左子树,开始遍历其左子树
            push(s,x);
            p=p->lchild;
        }
    
        while (!StackEmpty(s) && s.Elem[s.top].tag==R)  
        {
            x = pop(s);
            p = x.ptr;
            visite(p->data);   //tag为R,表示右子树访问完毕,故访问根结点       
        }
        
        if (!StackEmpty(s))
        {
            s.Elem[s.top].tag =R;     //遍历右子树;左子树到头了,所以要开始遍历右子树
            p=s.Elem[s.top].ptr->rchild;        
        }    
    }while (!StackEmpty(s));
}//PostOrderUnrec 

struct Node {
    int data;
    Node *left;
    Node *right;
};

struct PostNode {
    Node *node;
    int type;//0 左;1 右
};

void post(Node *root) {
    stack<PostNode> st;
    Node *t = root;

    do 
    {
        while(t!=NULL) {
            PostNode pn;
            pn->node = t;
            pn.type = 0;
            st.push(pn);
            t = t->left;
        }

        while(!st.empty() && st.top().type == 1) {
            cout<<st.top().node->data<<endl;
            st.pop();
        }

        if (!st.empty()) {
            st.top().type = 1;
            t = st.top().node->right;
        }
    } while (!st.empty());
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值