Ruby DFS solution


  • 0
    T

    Uses a '#' to denote the end of a branch.

    # Encodes a tree to a single string.
    #
    # @param {TreeNode} root
    # @return {string}
    def serialize(root)
        return "#" if root.nil?
        return [root.val, serialize(root.left), serialize(root.right)].flatten.join(',')
    end
    
    # Decodes your encoded data to tree.
    #
    # @param {string} data
    # @return {TreeNode}
    def deserialize(data)
        return nil if data.nil?
        des_list(data.split(','))
    end
    
    def des_list(nodes)
        val = nodes.shift
        return nil if val == '#'
        node = TreeNode.new val
        node.left = des_list(nodes)
        node.right = des_list(nodes)
        return node
    end
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.