MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / insert

Function insert

data_structures/binary_tree/inorder_tree_traversal_2022.py:17–43  ·  view source on GitHub ↗

If the binary search tree is empty, make a new node and declare it as root. >>> node_a = BinaryTreeNode(12345) >>> node_b = insert(node_a, 67890) >>> node_a.left_child == node_b.left_child True >>> node_a.right_child == node_b.right_child True >>> node_a.data == node

(node: BinaryTreeNode | None, new_value: int)

Source from the content-addressed store, hash-verified

15
16
17def insert(node: BinaryTreeNode | None, new_value: int) -> BinaryTreeNode | None:
18 """
19 If the binary search tree is empty, make a new node and declare it as root.
20 >>> node_a = BinaryTreeNode(12345)
21 >>> node_b = insert(node_a, 67890)
22 >>> node_a.left_child == node_b.left_child
23 True
24 >>> node_a.right_child == node_b.right_child
25 True
26 >>> node_a.data == node_b.data
27 True
28 """
29 if node is None:
30 node = BinaryTreeNode(new_value)
31 return node
32
33 # binary search tree is not empty,
34 # so we will insert it into the tree
35 # if new_value is less than value of data in node,
36 # add it to left subtree and proceed recursively
37 if new_value < node.data:
38 node.left_child = insert(node.left_child, new_value)
39 else:
40 # if new_value is greater than value of data in node,
41 # add it to right subtree and proceed recursively
42 node.right_child = insert(node.right_child, new_value)
43 return node
44
45
46def inorder(node: None | BinaryTreeNode) -> list[int]: # if node is None,return

Callers 1

make_treeFunction · 0.70

Calls 1

BinaryTreeNodeClass · 0.85

Tested by

no test coverage detected