Serialization then string find, python 95ms


  • 0
    Z

    I remember there is a problem in leetcode which asks to serialize a binary tree, this solution is based on that, it is not the best way but easy to remember and write

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def isSubtree(self, s, t):
            """
            :type s: TreeNode
            :type t: TreeNode
            :rtype: bool
            """
            def dfs(root):
                if not root:
                    return "null"
                return "%s,%s,%s" % (root.val, dfs(root.left), dfs(root.right))
            return (',' + dfs(s)).find(',' + dfs(t)) != -1
    

  • 1

    Has a bug, doesn't get accepted anymore.


  • 0
    Z

    thanks, fixed, the bug is that when there is only one node, such as [12], [2], then the string find will fail


Log in to reply
 

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