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

    #include<iostream>
    #include<stack>
    using namespace std;
    /*二叉树的前序遍历,按照  根节点->左孩子->右孩子
    
    */
    
    typedef struct node
    {
        char data;
        struct node *lchild,*rchild;
    }BinTree;
    void creatBinTree(BinTree * &root){    
        char ch;
        if(ch=getchar()){
            if(ch=='#')
            root=NULL;
        else{
            root=new BinTree;
            root->data=ch;
            creatBinTree(root->lchild);
            creatBinTree(root->rchild);
        }
     }
    }
    //创建二叉树,
    //递归遍历
    void preOrder1(BinTree *&root){  //root是指向BinTree的结构体变量
        if(root){
            cout<<root->data<<" ";
            preOrder1(root->lchild);
            preOrder1(root->rchild);
        }
    }
    //非递归操作
    
    void InOrder(BinTree * & root){
        if(root){
            InOrder(root->lchild);
            cout<<root->data<<" ";
            InOrder(root->rchild);
        }
    }
    void PostOrder(BinTree * &root){
        if(root){
            PostOrder(root->lchild);
            PostOrder(root->rchild);
            cout<<root->data<<" ";
        }
    }
    int main(){        
            BinTree * root;
            creatBinTree(root);
            cout<<"前序遍历:";
            preOrder1(root);
            cout<<endl;
            cout<<"中序遍历:";
            InOrder(root);
            cout<<endl;
            cout<<"后序遍历:";
            PostOrder(root);
            cout<<endl;
            system("pause");
        return 0;
    }

    比如输入 

    AB##C##

    前序:A B C

    中序:B A C

    后序:B C A

  • 相关阅读:
    11.06第十次作业
    (构造方法私有化、this)10.29练习题
    10.23创造人
    10.16(RuPeng)游戏
    10.09
    作业9.25
    练习题
    (随机数之和)求一整数各位数之和1636050052王智霞
    两点之间的距离1636050052王智霞
    TabLayout 简单使用。
  • 原文地址:https://www.cnblogs.com/wintersong/p/4598578.html
Copyright © 2011-2022 走看看