非递归遍历二叉树

题意:

二叉树的建立以及各类算法。

用先序次序输入创建二叉树,然后:

1)先序非递归输出

2)中序非递归输出

3)求树高度

 

输入:ABD##E##C##

输出:

ABDEC

DBEAC

 

 

题解:暴力模拟遍历过程,指针动态建树。

求树高的话,可以发现遍历时栈的大小就是树高。

#include<iostream>
#include<string>
#include<stack>
#include<algorithm>
using namespace std;
string S;
int N;
struct node{
    char data;
    node *lson,*rson;
};
void build(node* &rt){
    char c=S[N++];
    if(c=='#')rt=NULL;//**标记为空**
    else{
        if(!rt)return;
        rt=new node;rt->data=c;    
        build(rt->lson);build(rt->rson);        
    }
}
void pre(node* rt){
    cout<<rt->data<<endl;
    if(rt->lson)pre(rt->lson);
    if(rt->rson)pre(rt->rson);
}
void mid(node* rt){    
    if(rt->lson)mid(rt->lson);
    cout<<rt->data<<endl;
    if(rt->rson)mid(rt->rson);
}
void _pre(node* rt){
    node *cur=rt;
    stack<node*> S;
    while(cur||!S.empty()){
        while(cur){
            cout<<cur->data<<endl;
            S.push(cur);
            cur=cur->lson;
        }
        if(!S.empty()){
            cur=S.top();
            S.pop();
            cur=cur->rson;
        }
    }
}
void _mid(node* rt){
    node *cur=rt;
    stack<node*> S;
    while(cur||!S.empty()){
        while(cur){
            S.push(cur);
            cur=cur->lson;
        }
        if(!S.empty()){
            cur=S.top();
            cout<<cur->data<<endl;
            S.pop();
            cur=cur->rson;
        }
    }
}
int  height(node *rt){
    int ret=0;
    node *cur=rt;
    stack<node*> S;
    while(cur||!S.empty()){
        while(cur){
            S.push(cur);
            cur=cur->lson;
        }
        if(!S.empty()){
            cur=S.top();
            ret=max((int)S.size(),ret);
            S.pop();
            cur=cur->rson;
        }
    }
    return ret;
}
int main(){
    cin>>S;
    N=0;
    node *BT;
    build(BT);
    _pre(BT);
    cout<<endl;
    _mid(BT);
    cout<<endl;
    cout<<height(BT);
}
/*
     ABD##E##C##   
*/
/*
    A
  B    C
D   E
*/

 

转载于:https://www.cnblogs.com/SuuT/p/9582690.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值