[LeetCode][Python3] 297. Serialize and Deserialize Binary Tree
2019. 3. 25. 00:24 |
프로그래밍/LeetCode
Problem :
https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
My Solution :
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
def preorder(root, tree):
if root:
tree.append(root.val)
preorder(root.left, tree)
preorder(root.right, tree)
else:
tree.append('N')
tree = []
preorder(root, tree)
return ','.join(map(str, tree))
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
def build(data):
val = data.pop()
if val == 'N':
return
node = TreeNode(int(val))
node.left = build(data)
node.right = build(data)
return node
data = data.split(',')
data = data[::-1]
return build(data)
'프로그래밍 > LeetCode' 카테고리의 다른 글
[LeetCode][Python3] 73. Set Matrix Zeroes (0) | 2019.03.27 |
---|---|
[LeetCode][Python3] 329. Longest Increasing Path in a Matrix (0) | 2019.03.27 |
[LeetCode][Python3] 264. Ugly Number II (0) | 2019.03.26 |
[LeetCode][Python3] 334. Increasing Triplet Subsequence (0) | 2019.03.25 |
[LeetCode][Python3] 105. Construct Binary Tree from Preorder and Inorder Traversal (0) | 2019.03.24 |
[LeetCode][Python3] 131. Palindrome Partitioning (0) | 2019.03.23 |
[LeetCode][Python3] 128. Longest Consecutive Sequence (0) | 2019.03.23 |
[LeetCode][Python3] 42. Trapping Rain Water (0) | 2019.03.23 |
최근에 달린 댓글 최근에 달린 댓글