题解 | #序列化二叉树#

序列化二叉树

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;
    }
};
全部评论

相关推荐

06-12 17:46
门头沟学院 Java
运营你豪哥:来说重点: ​1.项目前置,时间倒序。​​ 2.​项目描述强化结果与量化效果(STAR原则里的R)。​​ ​3.个人技能精炼,明确掌握程度,突出核心。​​ ​4.增加强有力开头的个人总结部分。​​ 5.​优化教育背景(成绩排名)、合并奖项与活动。​​
听劝,我这个简历该怎么改...
点赞 评论 收藏
分享
白火同学:大二有这水平很牛了,可以适当对关键信息加粗一点,比如关键技术、性能指标之类的。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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