二叉树后序遍历

分别用了三种不同的方法实现了二叉树的后序遍历。

/*
input:
2
10 5 4 -1 -1 -1 20 19 -1 -1 40 -1 -1
30 10 8 20 -1 -1 -1 -1 50 40 -1 45 -1 -1 -1
output:
4 5 19 40 20 10
20 8 10 45 40 50 30
*/
#include<iostream>
#include<stack>
using namespace std;
struct BTreeNode{
    //二叉树
    int data;
    BTreeNode *lchild;
    BTreeNode *rchild;
    BTreeNode *parent;
};
struct snode{
    //设置访问标识
    BTreeNode *node;
    bool flag;
};
/*
void PostOrder(BTreeNode *t){
    //递归方法
    if(t == NULL)return ;
    PostOrder(t->lchild);
    PostOrder(t->rchild);
    cout<<t->data<<' ';
}
*/
/*
void PostOrder(BTreeNode *t){
    //设置访问标识,第一次为访问完左子树,第二次为访问完右子树。二次访问即刻输出结点。
    stack<snode> s;
    snode temp;
    while(!s.empty() || t != NULL){
        while(t != NULL){
            temp.node = t;
            temp.flag = false;
            s.push(temp);
            t = t->lchild;
        }
        if(!s.empty()){
            temp = s.top();
            s.pop();
            t = temp.node;
            if(temp.flag){
                cout<<t->data<<' ';
                t = NULL;
            }
            else{
                temp.flag = true;
                s.push(temp);
                t = t->rchild;
            }
        }
    }
}
*/
void PostOrder(BTreeNode *t){
    //采取根右左的存放方式,用栈实现后序遍历。设置访问标识,注意第一次放入栈,放入的是根,第二次调整其顺序。
    stack<snode> s;
    snode temp,ltemp,rtemp;
    temp.node = t;
    temp.flag = false;
    s.push(temp);
    while(!s.empty()){
        temp = s.top();
        s.pop();
        if(temp.flag)cout<<temp.node->data<<' ';
        else{
            temp.flag = true;
            s.push(temp);
            if(temp.node->rchild != NULL){
                rtemp.flag = false;
                rtemp.node = temp.node->rchild;
				s.push(rtemp);
            }
            if(temp.node->lchild != NULL){
                ltemp.flag = false;
                ltemp.node = temp.node->lchild;
				s.push(ltemp);
            }

        }
    }
}
void Create(BTreeNode *&t){
    //(测试用)以先序遍历构建二叉树
	int x;
	cin>>x;
	if(x == -1)
		t = NULL;
	else
	{
		t = new BTreeNode;
		t->data = x;
		Create(t->lchild);
		Create(t->rchild);
	}
}
int main(){
	BTreeNode *root = NULL;
	int t;
	cin>>t;
	while(t--)
	{
		Create(root);
		PostOrder(root);
		cout<<endl;
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值