# Time:  O(n)
# Space: O(h)

"""
# Definition for a Node.
class Node(object):
    def __init__(self, val, children):
        self.val = val
        self.children = children
"""
class Codec:

    def serialize(self, root):
        """Encodes a tree to a single string.
        
        :type root: Node
        :rtype: str
        """
        def dfs(node, vals):
            if not node:
                return
            vals.append(str(node.val))
            for child in node.children:
                dfs(child, vals)
            vals.append("#")
        
        vals = []
        dfs(root, vals)
        return " ".join(vals)


    def deserialize(self, data):
        """Decodes your encoded data to tree.
        
        :type data: str
        :rtype: Node
        """
        def isplit(source, sep):
            sepsize = len(sep)
            start = 0
            while True:
                idx = source.find(sep, start)
                if idx == -1:
                    yield source[start:]
                    return
                yield source[start:idx]
                start = idx + sepsize
        
        if not data:
            return None
    
        vals = iter(isplit(data, ' '))
        root = Node(int(next(vals)), [])
        stack = [root]
        for val in vals:
            if val == "#":
                stack.pop()
            else:
                node = Node(int(val), [])
                stack[-1].children.append(node)
                stack.append(node)
        return root
        

# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))

@@ -1105,32 +1105,40 @@
 sepsize%0A        
+        
 %0A        if not 
@@ -1134,19 +1134,21 @@
     
-if not data
+def dfs(vals)
 :%0A  
@@ -1161,33 +1161,37 @@
     
-return None
+val = next(vals)
 %0A    
-%0A
         
 vals
@@ -1190,39 +1190,55 @@
     
+if 
 val
-s
  =
- iter(isplit(data, ' '))%0A
+= %22#%22:%0A                return None%0A    
     
@@ -1257,26 +1257,19 @@
 ode(int(
-next(
 val
-s)
 ), %5B%5D)%0A 
@@ -1279,47 +1279,29 @@
     
-stack = %5Broot%5D%0A        for val in 
+    child = dfs(
 vals
-:
+)
 %0A   
@@ -1305,37 +1305,35 @@
             
-if val == %22#%22
+while child
 :%0A          
@@ -1342,182 +1342,188 @@
     
-stack.pop()%0A            else:%0A                node = Node(int(val), %5B%5D)%0A                stack%5B-1%5D.children.append(node)%0A                stack.append(node)%0A        return root
+root.children.append(child)%0A                child = dfs(vals)%0A            return root%0A%0A        if not data:%0A            return None%0A    %0A        return dfs(iter(isplit(data, ' ')))
 %0A   

Update serialize-and-deserialize-n-ary-tree.py