class TreeNode:
def __init__(self, value):
# Initialize a tree node with a given value.
self.value = value
self.left = None # Left child of the node
self.right = None # Right child of the node
def insert_into_bst(root, value):
if root is None:
# If the tree is empty, create a new node with the given value and return it.
return TreeNode(value)
if value < root.value:
# If the value is less than the root node's value, insert it into the left subtree.
root.left = insert_into_bst(root.left, value)
else:
# If the value is greater than or equal to the root node's value, insert it into the right subtree.
root.right = insert_into_bst(root.right, value)
return root
def find_depth_recursive(root, target, depth=0):
if root is None:
# If the current node is None, the target is not found in the tree.
return -1
if root.value == target:
# If the current node's value matches the target, return the current depth.
return depth
elif target < root.value:
# If the target value is less than the current node's value, search in the left subtree.
return find_depth_recursive(root.left, target, depth + 1)
else:
# If the target value is greater than the current node's value, search in the right subtree.
return find_depth_recursive(root.right, target, depth + 1)
# Driver code
if __name__ == "__main__":
# List of values to be inserted into the BST.
values = [15, 10, 20, 8, 12, 17, 25]
# Initialize the root of the BST as None.
root = None
# Insert each value into the BST.
for value in values:
root = insert_into_bst(root, value)
# Define the target value to find in the BST.
target = 20
# Find the depth of the node with the target value.
depth = find_depth_recursive(root, target)
# Print the depth of the node with the target value.
print(f"Depth of node {target}:", depth)