题解 | #序列化二叉树#

序列化二叉树

http://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84

通过前序遍历或层次遍历(递归 或 非递归)去建树

注意char* 的使用

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    char* Serialize(TreeNode *root) {    
        if(!root)
            return NULL;
        queue<TreeNode*> q;
        int* s = new int[101];
        int count = 0;
        q.push(root);
        while(!q.empty()){
            TreeNode* temp = q.front();
            if(temp)
                s[count] = temp->val;
            else
                s[count] = -1;
            count ++;
            if(temp){
                q.push(temp->left);
                q.push(temp->right);
            }
            q.pop();
        }
        return (char*)s;
    }
    TreeNode* Deserialize(char *str) {
        if(!str)
            return NULL;
        int* t = (int*)str;
        TreeNode* root = new TreeNode(t[0]);
        queue<TreeNode*> q;
        int count = 1;
        q.push(root);
        while(!q.empty()){
            TreeNode* temp = q.front();
            if(t[count] != -1){
                temp->left = new TreeNode(t[count]);
                q.push(temp->left);
            }
            count ++;
            if(t[count] != -1){
                temp->right = new TreeNode(t[count]);
                q.push(temp->right);
            }
            count ++;
            q.pop();
        }
        return root;
    }
};
全部评论

相关推荐

萧索X:写篮球联赛干嘛,陪老板打篮球吗。还有实习经历要写自己所在岗位具体完成什么工作,自己的任务具体完成了什么需求,给公司带来了哪些量化增长
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务