【剑指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;
}

 

posted @ 2019-09-19 02:34  Joel_Wang  阅读(248)  评论(0编辑  收藏  举报