Recursion can be used to traverse a binary tree in a depth-first manner, visiting nodes in a specific order.
In this example, we'll create a simple binary tree data structure and
perform an inorder traversal using recursion. An inorder traversal
visits nodes in a binary tree in the order of left subtree, current
node, and right subtree. This traversal is often used to print the nodes
of a binary search tree.
Advertise on this site. I promise you will like the rates :)
Here's a breakdown of the key components of the example:
We define a struct TreeNode to represent a node in the binary tree. Each node contains an integer data, a pointer to the left child (left), and a pointer to the right child (right).
The createNode function is used to create a new binary tree node with the given data. It dynamically allocates memory for the node and initializes its fields.
The inorderTraversal function performs an inorder traversal of the binary tree using recursion. It follows the left-subtree-current-node-right-subtree order.
In the main function, we create a sample binary tree and then perform an inorder traversal to print the values of the nodes.
When you run the program, it will create the binary tree:
The inorder traversal will print the values of the nodes:
We've just demonstrated how recursion can be used to perform an inorder traversal of a binary tree, visiting nodes in a specific order. The example highlights the power and elegance of recursion in solving problems related to hierarchical data structures like binary trees.