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;
    }
  • 相关阅读:
    字符串数组 去重 研究
    监听 dom 改变
    清除body 不改变路径 页面信息加载第三方
    使用img标签实现xss的常见方法
    禁止ios浏览器页面上下滚动 (橡皮筋效果)
    遍历 Request.Form.Keys
    selenium-java之使用浏览器打开网页举例
    docker搭建redis
    docker镜像无法删除 Error:No such image:xxxxxx
    连接查询SQL说明举例
  • 原文地址:https://www.cnblogs.com/joelwang/p/11546562.html
Copyright © 2011-2022 走看看