class Node { constructor(value) { this.value = value; this.left = null; this.right = null; } } const root = new Node(10); root.left = new Node(5); root.right = new Node(15); root.left.left = new Node(3); root.left.right = new Node(7); function inorder(node, result = []) { if (!node) return; inorder(node.left, result); result.push(node.value); inorder(node.right, result); return result; } console.log(inorder(root));
Inorder traversal visits nodes in the order: left subtree, root, right subtree.
For the given tree, the nodes are visited as 3 (leftmost), 5 (parent of 3 and 7), 7 (right child of 5), 10 (root), and 15 (right child of root).
class Node { constructor(value) { this.value = value; this.left = null; this.right = null; } } const root = new Node(42); function inorder(node, result = []) { if (!node) return; inorder(node.left, result); result.push(node.value); inorder(node.right, result); return result; } console.log(inorder(root));
Inorder traversal visits left, root, right. Since there are no children, only the root value 42 is returned.
function inorder(node, result = []) {
if (!node) return result;
inorder(node.left, result);
result.push(node.value);
inorder(node.right, result);
return result;
}
const root = { value: 1, left: null, right: null };
console.log(inorder(root));The base case returns the result array immediately when node is null. This causes the recursive calls to return early and skip some nodes.
The correct base case should return nothing (undefined) to allow recursion to continue properly.
class Node { constructor(value) { this.value = value; this.left = null; this.right = null; } } const root = new Node(8); root.right = new Node(10); root.right.right = new Node(14); root.right.right.left = new Node(13); function inorder(node, result = []) { if (!node) return; inorder(node.left, result); result.push(node.value); inorder(node.right, result); return result; } console.log(inorder(root));
The traversal visits 8 (root), then moves to right subtree.
In right subtree, it visits left child 13, then 14, then 10.
So the order is 8, 10, 13, 14.
A full binary tree of height 3 has 2^3 - 1 = 7 nodes.
Inorder traversal visits all nodes exactly once, so it visits 7 nodes.