zoukankan      html  css  js  c++  java
  • 非递归遍历二叉树

    题意:

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

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

    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
    */
    成功的路并不拥挤,因为大部分人都在颓(笑)
  • 相关阅读:
    GridView中获取UserControl Fred
    objectivec字符串类NSString的使用
    IPhone之AVAudioRecorder
    iPhone中用第三方工具(RegexKitLite)实现正则表达
    android实现底部菜单栏
    android 菜单设计
    Objective C内存管理——如何理解autorelease
    在iphone中使用正则表达式 — OgreKit 详解
    iphone开发者证书装多台电脑的方法
    iPhone sdk 4.0 正则表达式
  • 原文地址:https://www.cnblogs.com/SuuT/p/9582690.html
Copyright © 2011-2022 走看看