题解 | #序列化二叉树# JS Node 实现

序列化二叉树

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

function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
}

function Serialize(pRoot) {
    if (pRoot === null) return "#";

    var res = [];
    SerializeFunc(pRoot, res);
    return res.join("");
}

function SerializeFunc(root, str) {
    if (root === null) {
        str.push('#');
        return;
    }

    str.push(root.val + '!');
    SerializeFunc(root.left, str);
    SerializeFunc(root.right, str);
}

function Deserialize(s) {
    if (s === "#") return null;
    var index = { val: 0 }; // 使用对象包装index,以在递归中共享引用

    return DeserializeFunc(s, index);
}

function DeserializeFunc(s, index) {
    if (index.val >= s.length) {
        return null;
    }

    var c = s.charAt(index.val);
    if (c === '#') {
        index.val++;
        return null;
    }

    var isNegative = false;
    if (c === '-') {
        isNegative = true;
        index.val++;
    }

    var val = 0;
    while (index.val < s.length && s.charAt(index.val) !== '!') {
        val = val * 10 + parseInt(s.charAt(index.val));
        index.val++;
    }

    if (isNegative) {
        val *= -1;
    }

    var root = new TreeNode(val);

    if (index.val < s.length) {
        index.val++; // 跳过 '!'
        root.left = DeserializeFunc(s, index);
        root.right = DeserializeFunc(s, index);
    }

    return root;
}

module.exports = {
    Serialize: Serialize,
    Deserialize: Deserialize
};

全部评论

相关推荐

点赞 评论 收藏
分享
11-02 09:49
已编辑
货拉拉_测试(实习员工)
热爱生活的仰泳鲈鱼求你们别卷了:没事楼主,有反转查看图片
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务