1. In-order: left, self, right
Visiting self between the children yields sorted order for a BST.
inorder(root.left, result);
result.push(root.val);
inorder(root.right, result)Typorithm · easy
Step 1 of 8 · intro card
Trees
Three DFS orders differ only by WHERE you record the node: before, between, or after recursing into the children.
All three traversals recurse left then right; only the position of the push changes.
Pre-order records the node first (top-down), in-order between the children (sorted for a BST), post-order last (bottom-up).
The shared skeleton makes the visit position the single distinguishing idea.
Pre: self, left, right.
In: left, self, right.
Post: left, right, self.
function inorder(root, result = []) {
if (root === null) {
return result;
}
inorder(root.left, result);
result.push(root.val);
inorder(root.right, result);
return result;
}
function preorder(root, result = []) {
if (root === null) {
return result;
}
result.push(root.val);
preorder(root.left, result);
preorder(root.right, result);
return result;
}
function postorder(root, result = []) {
if (root === null) {
return result;
}
postorder(root.left, result);
postorder(root.right, result);
result.push(root.val);
return result;
}Connect each part of the code to the concept before you type.
Visiting self between the children yields sorted order for a BST.
inorder(root.left, result);
result.push(root.val);
inorder(root.right, result)Recording the node before its children captures structure top-down.
result.push(root.val);
preorder(root.left, result);
preorder(root.right, result)Recording the node after its children processes leaves first.
postorder(root.left, result);
postorder(root.right, result);
result.push(root.val)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.