DFS — Inorder Traversal (Left, Root, Right)
DSA · Treessyntax
Visit left subtree → process node → visit right subtree.
For BST: inorder gives sorted order.example
// JavaScript
function inorder(root) {
const result = [];
function dfs(node) {
if (!node) return;
dfs(node.left);
result.push(node.val);
dfs(node.right);
}
dfs(root);
return result;
}
// Iterative with stack
function inorderIterative(root) {
const result = [], stack = [];
let current = root;
while (current || stack.length) {
while (current) {
stack.push(current);
current = current.left;
}
current = stack.pop();
result.push(current.val);
current = current.right;
}
return result;
}
# Python
def inorder(root):
result = []
def dfs(node):
if not node:
return
dfs(node.left)
result.append(node.val)
dfs(node.right)
dfs(root)
return resultoutput
Tree: 4
/ \
2 6
/ \
1 3
Inorder: [1, 2, 3, 4, 6]Note Time O(n), Space O(h) where h = tree height. For balanced tree h = log n, for skewed h = n. Know both recursive and iterative versions — interviewers may ask for iterative. Inorder on BST is a common trick to verify sorted property.