defserialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ if root isNone: return"#" c = str(root.val) lc = self.serialize(root.left) rc = self.serialize(root.right) returnf'{c},{lc},{rc}' defdeserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ s = data.split(',') return dfs(s, [0])
classSolution: deffindTarget(self, root: TreeNode, k: int) -> bool: defdfs(node, m, k): if node isNone: return if k - node.val in m: self.res = True return m[node.val] = True dfs(node.left, m, k) dfs(node.right, m, k) m = {} self.res = False dfs(root, m, k) return self.res