This function inserts a node with value val into the BST
(root: Optional[Node], val: int)
| 3 | |
| 4 | |
| 5 | def insert(root: Optional[Node], val: int) -> Node: |
| 6 | """This function inserts a node with value val into the BST""" |
| 7 | |
| 8 | # If the tree is empty, create a new node |
| 9 | if root is None: |
| 10 | return Node(val) |
| 11 | |
| 12 | # If the value to be inserted is less than the root value, insert in the left subtree |
| 13 | if val < root.data: |
| 14 | root.left = insert(root.left, val) |
| 15 | |
| 16 | # If the value to be inserted is greater than the root value, insert in the right subtree |
| 17 | else: |
| 18 | root.right = insert(root.right, val) |
| 19 | return root |