def build_tree(): val = vals.popleft() if val != 'null': node = TreeNode(int(val)) node.left = build_tree() node.right = build_tree() return node else: return None
def helper(l, r): nonlocal head # 将head声明为外层变量 if l > r: return None mid = (l + r) // 2 left = helper(l, mid - 1) root = TreeNode(head.val) root.left = left head = head.next root.right = helper(mid + 1, r) return root
def helper(n): if n == 1: return [TreeNode(0)] i, res = 1, [] while i < n - 1: left, right = helper(i), helper(n - 1 - i) for x in left: for y in right: root = TreeNode(0) root.left = x root.right = y res.append(root) i += 2 return res
def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ vals = collections.deque(data.split()) def build_tree(): val = vals.popleft() if val != 'null': node = TreeNode(int(val)) node.left = build_tree() node.right = build_tree() return node else: return None return build_tree() # Your Codec object will be instantiated and called as such: codec = Codec() t = TreeNode(5) t.left = TreeNode(2) t.left.right = TreeNode(4) t.right = TreeNode(9) root = codec.deserialize(codec.serialize(t)) Tree().front_recursion(root)