javascript-leetcode icon indicating copy to clipboard operation
javascript-leetcode copied to clipboard

297. 二叉树的序列化与反序列化

Open Geekhyt opened this issue 4 years ago • 0 comments

原题链接

递归 dfs

const serialize = function(root) {
    const res = []
    function dfs(node) {
        if (node === null) {
            res.push(null)
            return
        }
        res.push(node.val)
        dfs(node.left)
        dfs(node.right)
    }
    dfs(root)
    return res
}
  • 时间复杂度: O(n)
  • 空间复杂度: O(n)
const deserialize = function(data) {
    function dfs() {
        if (data.length === 0) return null
        let val = data.shift()
        if (val === null) return null
        let node = new TreeNode(val)
        node.left = dfs()
        node.right = dfs()
        return node
    }
    return dfs()
}
  • 时间复杂度: O(n)
  • 空间复杂度: O(n)

Geekhyt avatar Sep 20 '21 14:09 Geekhyt