非递归遍历二叉树

题意:

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

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

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