preorder, postorder, inorder , DFS and BFS traversal can be applied to all types of trees
preorder, inorder, postorder, DFS, and BFS can be applied to all types of trees, not just binary trees. But the implementation changes slightly depending on whether it’s a binary tree or a general tree (where nodes can have more than two children).
Let’s go step by step 👇
🌳 1. What Is Tree Traversal?
Traversal means visiting every node exactly once in a specific order — to print values, search, or perform some computation.
🌿 2. DFS vs BFS (Applies to All Trees)
Type Meaning Works on
DFS (Depth-First Search) Go as deep as possible before backtracking ✅ All trees BFS (Breadth-First Search) Visit level by level (top to bottom) ✅ All trees
🌲 DFS (Depth-First Search)
There are 3 main orders in binary trees, but the concept extends to all trees.
Type Visit Order Applies to
Preorder Visit root → then children ✅ All trees Postorder Visit children → then root ✅ All trees Inorder Left → Root → Right ⚠️ Only for binary trees
🌼 3. Traversals in Binary Tree
Let’s use this binary tree:
A
/ \
B C
/ \
D E
Traversal Visit Order Result
Preorder Root → Left → Right A B D E C Inorder Left → Root → Right D B E A C Postorder Left → Right → Root D E B C A BFS (Level order) Level by level A B C D E
🌵 4. Traversals in General (N-ary) Tree
A
/|\
B C D
/ \
E F
✅ Preorder (Root first)
Visit A, then recursively traverse its children from left to right.
Order: A B C E F D
✅ Postorder (Root last)
Visit all children first, then the root.
Order: B E F C D A
⚠️ Inorder — ❌ Not applicable
Because “Inorder” needs a clear left and right, which doesn’t exist in a general tree.
✅ BFS (Level Order)
Visit level by level using a queue.
Order: A B C D E F
⚙️ 5. Implementation Difference
🧩 Binary Tree (Java-like)
void preorder(Node root) { if (root == null) return; System.out.print(root.data + " "); preorder(root.left); preorder(root.right); }
🧩 General Tree (N children)
void preorder(TreeNode root) { if (root == null) return; System.out.print(root.val + " "); for (TreeNode child : root.children) preorder(child); }
Both are DFS traversals, but the second supports any number of children.
🧠 6. Summary
Traversal Binary Tree N-ary Tree Notes
Preorder ✅ ✅ Root before children Inorder ✅ ❌ Only for binary (left/right) Postorder ✅ ✅ Root after children DFS ✅ ✅ Depth-first search (includes all 3 above) BFS ✅ ✅ Level-order traversal
🪴 7. Quick Memory Tip
Order Visit Root When? Example
Preorder Before children “PRE” → first Inorder Between children “IN” → in between Postorder After children “POST” → last
✅ In summary:
Preorder, Postorder, DFS, and BFS → work on all trees.
Inorder → only applies to binary trees (because you must have a “left” and “right”).