zoukankan      html  css  js  c++  java
  • 【剑指offer37】二叉树的序列化

    序列化过程很简单,如果是采用先序序列,那么对先序遍历做出改变即可;

    层序遍历建立二叉树,如:

             1

        2        3

    4   #     5   6

    输入第一行:将要输入的节点的个数N,如上面的为7;

    第二行:输入N个节点,

    #include <iostream>
    #include <string>
    
    #include <vector>
    #include <queue>
    
    using namespace std;
    
    struct treeNode{
        int val;
        treeNode *left;
        treeNode *right;
        treeNode(){}
        treeNode(int x):
            val(x),left(NULL),right(NULL){}
    };
    
    int s_to_i(string str){
        int v=0;
        unsigned int i=0;
        while(i<str.size()){
            v=v*10+str[i]-'0';
        }
        return v;
    }
    treeNode* buildTree(int N){
        if(N==0){
            return NULL;
        }
    
        int i=1;
        int v=0;
        char c;
    
        cin>>c;
        if(c=='#') return NULL;
    
        v=c-'0';
    
        queue<treeNode*> q;
        treeNode *root=new treeNode(v);
        q.push(root);
    
        while(i<N&&!q.empty()){
            treeNode *node=q.front();
            q.pop();
    
            if(i<N){
                cin>>c;i++;
                if(c!='#'){
                    v=c-'0';
                    treeNode *lchild=new treeNode(v);
                    node->left=lchild;
                    q.push(lchild);
                }
            }
            if(i<N){
                cin>>c;i++;
                if(c!='#'){
                    v=c-'0';
                    treeNode *rchild=new treeNode(v);
                    node->right=rchild;
                    q.push(rchild);
                }
            }
        }
        return root;
    }
    void serialize(treeNode *root){
        if(root==NULL){
            cout<<'#'<<endl;return;
        }
        cout<<root->val<<endl;
        if(root->left!=NULL || root->right!=NULL)
            serialize(root->left);
        if(root->left!=NULL || root->right!=NULL)
            serialize(root->right);
    }
    int main()
    {
        int N;
        cin>>N;
        cout << "Build Tree" << endl;
        treeNode *root=buildTree(N);
        cout << "serialize Tree" <<endl;
        serialize(root);
        return 0;
    }
  • 相关阅读:
    UNIGUI与UNIURLFRAME的互动
    unigui结合JS方法记录
    如何将uniurlframe中html调用delphi的函数
    XE下显示托盘图标(TrayIcon)
    Delphi fmx控件在手机滑动与单击的问题
    Delphi使用iTools安卓模拟器
    Delphi调用SQL分页存储过程实例
    分享Pos函数(比FastPos还要快)
    Delphi Excel导入 的通用程序转载
    Delphi控件cxGrid 如何动态创建列?
  • 原文地址:https://www.cnblogs.com/joelwang/p/11546562.html
Copyright © 2011-2022 走看看