二叉树中序遍历

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

/*
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 10 19 20 40
20 8 10 30 40 45 50
*/
#include<iostream>
#include<stack>
using namespace std;
struct BTreeNode{
    //二叉树
    int data;
    BTreeNode *lchild;
    BTreeNode *rchild;
};
struct snode{
    //设置访问标识
    BTreeNode *node;
    bool flag;
};
/*
void InOrder(BTreeNode *t){
    //递归方法
    if(t == NULL)return ;
    InOrder(t->lchild);
    cout<<t->data<<' ';
    InOrder(t->rchild);
}
*/
/*
void InOrder(BTreeNode *t){
    //不断访问其左子树,然后输出其根,然后访问其接着的右子树,重复过程
    stack<BTreeNode*> s;
    while(!s.empty() || t != NULL){
        while(t != NULL){
            s.push(t);
            t = t->lchild;
        }
        if(!s.empty()){
            t = s.top();
            s.pop();
            cout<<t->data<<' ';
            t = t->rchild;
        }
    }
}
*/
void InOrder(BTreeNode *t){
    //按右根左的存放方式存入栈,根据栈的特性输出中序遍历。注意第一次放入的是根,第二次放入才调整其位置。
    stack<snode> s;
    snode temp,ltemp,rtemp;
    temp.flag = false;
    temp.node = t;
    s.push(temp);
    while(!s.empty()){
        temp = s.top();
        s.pop();
        if(temp.flag)cout<<temp.node->data<<' ';
        else{
            if(temp.node->rchild != NULL){
                rtemp.flag = false;
                rtemp.node = temp.node->rchild;
                s.push(rtemp);
            }
            temp.flag = true;
            s.push(temp);
            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);
		InOrder(root);
		cout<<endl;
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值