'Need help understanding Python recursion issue for 103. Binary Tree Zigzag Level Order Traversal

While solving Leetcode problem '103. Binary Tree Zigzag Level Order Traversal', I ran into issue that I am unable to understand why.

Following is the serialize logic I am using -


    def serialize(self, root):       
            if not root:
                return 'n'
            
            left = self.serialize(root.left)
            right = self.serialize(root.right)
            
            s =  str(root.val)+','+left+','+right
            return s 

To deserialize, I am checking the first character to take action and function is called recursively for rest of elements.

def deserialize(self, data):
        data = data.split(',')  # serialized string is comma separated with 'n' for Null 
        
        def buildTree(data):
            if not data:
                return None           
            
            if data[0] == 'n':
                data = data[1:]  # 0 index element is used. Use rest next time onwards
                return None
            
            root = TreeNode(int(data[0]))            
            data = data[1:] # 0 index element is used. Use rest next time onwards
            root.left = buildTree(data)
            root.right = buildTree(data)
            
            return root
        
        return buildTree(data)

However, this is not working. But following code with same logic is working. Just the change is I am popping the first element and not reassigning.

Difference in Above : data = data[1:] and Below code : data.pop(0)

def deserialize(self, data):
        
            data = data.split(',')

            def buildTree(data):
                if not data:
                    return None

                c = data.pop(0)
                if c == 'n':
                    return None

                root = TreeNode(int(c))

                root.left = buildTree(data)
                root.right = buildTree(data)

                return root
            return buildTree(data)

Can you help me understand what might be the issue here? As the list is mutable, it should work. Thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source