Python iterative preorder solution


  • 0
    C
    def serialize(self, root):
        stk, ser = [], []
        while stk or root:
            while root:
                ser.append(str(root.val))
                stk.append(root)
                root = root.left
            root = stk.pop().right
        return ' '.join(ser)
    
    def deserialize(self, data):
        dummy = TreeNode(float('inf'))
        stk = [dummy]
        for num in map(int, data.split()):
            cur = TreeNode(num)
            if num < stk[-1].val:
                stk[-1].left = cur
                stk.append(cur)
            else:
                while num > stk[-1].val:
                    tmp = stk.pop()
                tmp.right = cur
                stk.append(cur)
        return dummy.left

Log in to reply
 

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