Mental Model
Visit the left side first, then the middle, then the right side to see all parts in order.
Analogy: Like reading a book: first look at the left page, then the middle page, then the right page.
2 / \ 1 3 ā Start at root (2)
2 / \ 1 3 ā Start at root (2)
1 ā (at left child of 2) -> null 2 -> 3 -> null
Output: 1
Output: 1 2
3 ā (at right child of 2)
Output: 1 2 3
Output: 1 2 3
#include <stdio.h> #include <stdlib.h> // Define tree node typedef struct Node { int data; struct Node* left; struct Node* right; } Node; // Create new node Node* newNode(int data) { Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->left = NULL; node->right = NULL; return node; } // Inorder traversal: left, root, right void inorder(Node* root) { if (root == NULL) return; // base case: no node inorder(root->left); // visit left subtree printf("%d ", root->data); // visit root inorder(root->right); // visit right subtree } int main() { // Build tree: 2 with left 1 and right 3 Node* root = newNode(2); root->left = newNode(1); root->right = newNode(3); inorder(root); // print inorder traversal printf("\n"); return 0; }
if (root == NULL) return; // base case: no nodeinorder(root->left); // visit left subtreeprintf("%d ", root->data); // visit rootinorder(root->right); // visit right subtreeif (root == NULL) return; // base case: no node
if (root == NULL) return; // base case: no node
inorder(root->left); // visit left subtree
struct Node?2 / \ 1 3
void inorder(struct Node* root) {
if (root == NULL) return;
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}Pass the test and this pattern moves unknown