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 sortedListToBST(self, head): """ :type head: ListNode :rtype: TreeNode """ if not head: return None if not head.next: return TreeNode(head.val) slow = self.find_mid_node(head) root = TreeNode(slow.val) root.left, root.right = self.sortedListToBST( head), self.sortedListToBST(slow.next) 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)
def helper(l, r): if l > r: return None mid = (l + r) // 2 root = TreeNode(vals[mid]) root.left, root.right = helper(l, mid - 1), helper(mid + 1, r) return root
def helper(list): if not list: return None mid = len(list) // 2 root = TreeNode(list[mid]) root.left, root.right = helper(list[:mid]), helper(list[mid + 1:]) return root