Created
October 11, 2020 08:14
-
-
Save jonathanagustin/020a49b197b7ddbe6f3c55923ab06ffe to your computer and use it in GitHub Desktop.
Python Spartan DFS Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
https://leetcode.com/problems/serialize-and-deserialize-binary-tree/discuss/74259/Recursive-preorder-Python-and-C%2B%2B-O(n) | |
''' | |
class Codec: | |
def serialize(self, root): | |
def doit(node): | |
if node: | |
vals.append(str(node.val)) | |
doit(node.left) | |
doit(node.right) | |
else: | |
vals.append('#') | |
vals = [] | |
doit(root) | |
return ' '.join(vals) | |
def deserialize(self, data): | |
def doit(): | |
val = next(vals) | |
if val == '#': | |
return None | |
node = TreeNode(int(val)) | |
node.left = doit() | |
node.right = doit() | |
return node | |
vals = iter(data.split()) | |
return doit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment