def helper(l, lo, hi): if lo > hi: return mid = (lo + hi) >> 1 node = Node(l[mid]) node.left_child = helper(l, lo, mid - 1) node.right_child = helper(l, mid + 1, hi) return node
def convert_sorted_list_to_binary_search_tree(head): if head is None: return None #龟兔算法找节点 fast = head slow = head pre = None while fast is not None and fast.next is not None: fast = fast.next.next pre = slow slow = slow.next if pre is not None: # break link pre.next = None else: head = None #递归返回:当链表只有一个节点时 root = Node(slow.data) root.left_child = convert_sorted_list_to_binary_search_tree(head) root.right_child = convert_sorted_list_to_binary_search_tree(slow.next) return root
def test_node_right_child(self): n1 = Node(4) n2 = Node(6) n1.right_child = n2 self.assertEqual(n2, n1.right_child) self.assertEqual(6, n1.right_child.value)