Complete the code to create a new node with the given value.
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = [1] self.left = left self.right = right
The constructor assigns the passed value val to the node's val attribute.
Complete the code to append the serialized value to the result list.
def serialize(root): result = [] def helper(node): if not node: result.append('null') return result.append(str(node.[1])) helper(node.left) helper(node.right) helper(root) return ','.join(result)
We append the string form of the node's value (val) to the result list during serialization.
Fix the error in the deserialization code to correctly convert the string value to an integer.
def deserialize(data): values = data.split(',') def helper(): val = values.pop(0) if val == 'null': return None node = TreeNode([1]) node.left = helper() node.right = helper() return node return helper()
The serialized values are strings, so we convert val to an integer before creating the node.
Fill both blanks to complete the serialize function using preorder traversal.
def serialize(root): result = [] def helper(node): if node is None: result.append('null') return result.append(str(node.[1])) helper(node.[2]) helper(node.right) helper(root) return ','.join(result)
We append the node's value (val) and recursively call helper on the left child (left) first for preorder traversal.
Fill all three blanks to complete the deserialize function that rebuilds the tree.
def deserialize(data): values = data.split(',') def helper(): val = values.pop(0) if val == 'null': return [1] node = TreeNode([2]) node.left = helper() node.right = helper() return node return helper()
Return None for 'null' values, convert val to int for node creation, and use None for missing children.
