让 TreeNode 和list、dict等 一样支持str() 和 eval()
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
def func1(self, v,l=None,r=None):
self.val = v
self.left = l
self.right = r
def func2(self):
return 'TreeNode('+str(self.val) + ',' + str(self.left) + ',' + str(self.right) + ')'
TreeNode.__init__ = func1
TreeNode.__str__ = func2
class Solution:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
return str(root)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
return eval(data)