zoukankan      html  css  js  c++  java
  • 二叉树的操作

    在计蒜客上学了二叉树,感觉自己还学了点东西,就贴在这里吧

    #include<iostream>
    #include<string>
    using namespace std;
    class Node {
    public:
        char data;
        Node *lchild, *rchild;
        Node(int _data) {
            data = _data;
            lchild = NULL;
            rchild = NULL;
        }
        ~Node() {
            if (lchild != NULL) {
                delete lchild;
            }
            if (rchild != NULL) {
                delete rchild;
            }
        }
        void preorder(){   //先序遍历
            cout <<data<<" ";
            if(lchild!=NULL){
               lchild-> preorder();
            }
            if(rchild!=NULL){
               rchild-> preorder();
            }
        }
        void inorder(){   //中序遍历
           if(lchild!=NULL){
              lchild->inorder();
           }
            cout <<data<<" ";
            if(rchild!=NULL){
              rchild->inorder();
           }
        }
        void postorder() {   //后序遍历
            if (lchild != NULL) {
                lchild->postorder();
            }
            if (rchild != NULL) {
                rchild->postorder();
            }
            cout << data;
        }
        //已知先序和中序,求后序
        Node* build(const string &pre_str,const string &in_str,int len){
            Node* p=new Node(pre_str[0]-'0');
            int pos=in_str.find(pre_str[0]);
            if(pos>0){
                p->lchild=build(pre_str.substr(1,pos),in_str.substr(0,pos),pos);
            }
            if(len-pos-1>0){
               p->rchild=build(pre_str.substr(pos+1),in_str.substr(pos+1),len-pos-1);
            }
            return p;
        }
    };
    class BinaryTree {
    private:
        Node *root;
    public:
        BinaryTree() {
            root = NULL;
        }
        ~BinaryTree() {
            if (root != NULL) {
                delete root;
            }
        }
        BinaryTree(const string &pre_str,const string &in_str,int len){
           root=root->build(pre_str,in_str,len);
        }
        void preorder(){
           root->preorder();
        }
        void inorder(){
          root->inorder();
        }
        void postorder() {
            root->postorder();
        }
    };
    int main() {
        string pre_str;
        string in_str;
        cin>>pre_str;
        cin>>in_str;
        BinaryTree binarytree(pre_str,in_str,in_str.length());
        binarytree.postorder();
        cout <<endl;
        return 0;
    }
  • 相关阅读:
    搭建woocomerce网站
    Cozmo 机器人编程环境搭建
    DevExpress Wizard的控件使用方法
    DevExpress 地图的控件使用方法
    DevExpress 摄像机的控件使用方法
    大疆第一人称视角眼镜goggle激活
    iis支持asp.net4.0的注册命令使用方法
    【转】PowerDesigner删除外键关系,而不删除外键列
    【转】ABP webapi三种方式
    【转】OAuth2.0的refresh token
  • 原文地址:https://www.cnblogs.com/wangdongkai/p/5366288.html
Copyright © 2011-2022 走看看