To search for a node in a binary tree, you can use a recursive or iterative approach. Here’s an example implementation in Python:
- Recursive Approach
class Node: def __in it__ (self, value): self. value = value
self. left = Non self. right = None
- Iterative Approach
def search_ node iterative (root, target value): stack = [root]while stack: node = stack. pop ()if node is None:
continue if node.
In both implementations:
– We start at the root node of the binary tree.
– We compare the current node’s value with the target value.
– If we find a match, we return the node.
– If not, we recursively or iteratively traverse the left and right subtrees.
Example Usage
- Create a sample binary tree
root = Node (8)
root. Left = Node (3)
root. Right = Node (10)
root.left.left = Node (1)
root.left.right = Node (6) - Search for a node with value 6
result = search_node_recursive (root, 6)
if result is not None:
This code will output: Node found with value 6