This is one of those questions where knowing the terminology is necessary. In-order traversal visits the left child nodes first, then the root, followed by the right child (remember, it's called in-order because the current node's value is read in-between the left and right child nodes).
Recall the following ordering types:
Inorder traversal
- First, visit all the nodes in the left subtree
- Then the root node
- Visit all the nodes in the right subtree
When to use? With a BST, the in order traversal will give the elements in ascending order, useful for problems where order matters.
SNIPPET
1// pseudo-logic of the inorder function:
2inorder(root.left)
3display(root.data)
4inorder(root.right)
xxxxxxxxxx27
function inorderTraversal(root) { let res = []; helper(root, res); return res;}​function helper(root, res) { if (!root) { return res; } helper(root.left, res); res.push(root.val); helper(root.right, res); return res;}​const root = { val: 1, right: { val: 2, left: { val: 3 } }};​console.log(inorderTraversal(root));OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

