def _build_tree(arr): if not arr: return None mid = (0 + len(arr)) // 2 root = BinaryTreeNode(arr[mid]) root.left = _build_tree(arr[0:mid - 1]) root.right = _build_tree(arr[mid + 1:len(arr)]) return root
def _build_tree(s, e): if e < s: return None nonlocal l_node mid = s + (e - s) // 2 left = _build_tree(s, mid - 1) root = BinaryTreeNode(l_node.val) root.left = left l_node = l_node.next root.right = _build_tree(mid + 1, e) return root
def insert_bst(root: BinaryTreeNode, ins_node: BinaryTreeNode): if not root: return ins_node if ins_node.val == root.val: ori_left = root.left root.left = ins_node ins_node.left = ori_left return root elif ins_node.val > root.val: insert_bst(root.right, ins_node) else: insert_bst(root.left, ins_node)
def _gen_trees(s, e): ret = [] if s > e: ret.append(None) for idx in range(s, e + 1): left_trees = _gen_trees(s, idx - 1) right_trees = _gen_trees(idx + 1, e) for l, r in product(left_trees, right_trees): root = BinaryTreeNode(idx) root.left = l root.right = r ret.append(root) return ret
def left_rotate(node: BinaryTreeNode): right = node.right if right: node.right = right.left right.left = node return right return node
def right_rotate(node: BinaryTreeNode): left = node.left if left: node.left = left.right left.right = node return left return node
def generate_all_binary_trees(num_nodes): if num_nodes == 0: # Empty tree, add as a None. return [None] result = [] for num_left_tree_nodes in range(num_nodes): num_right_tree_nodes = num_nodes - 1 - num_left_tree_nodes left_subtrees = generate_all_binary_trees(num_left_tree_nodes) right_subtrees = generate_all_binary_trees(num_right_tree_nodes) # Generates all combinations of left_subtrees and right_subtrees. result += [ BinaryTreeNode(0, left, right) for left in left_subtrees for right in right_subtrees ] return result
else: if heap[i] > heap[2 * i + 1]: top = heap[i] heap[i] = heap[2 * i + 1] heap[2 * i + 1] = top i = 2 * i + 1 else: not_heap = False else: not_heap = False print(heap) return root if __name__ == '__main__': a = BinaryTreeNode(1) b = BinaryTreeNode(2) c = BinaryTreeNode(3) d = BinaryTreeNode(4) e = BinaryTreeNode(5) f = BinaryTreeNode(6) g = BinaryTreeNode(7) h = BinaryTreeNode(8) i = BinaryTreeNode(9) d.left = b d.right = f d.left.left = a d.left.right = c d.right.left = e d.right.right = g d.right.right.right = h