Binary tree inorder traversal
Easy TimeO(n) SpaceO(h)
In-order means visiting everything in a node's left subtree, then the node itself, then everything in its right subtree — the same three steps at every node, all the way down. Given the root of a binary tree, return its values in that order. Every node is visited exactly once, and an empty tree produces an empty list. Over a binary search tree the result comes out sorted.
Examples
Example 1
- Input
- node = buildTree()out = []
- Output
- The left subtree
[1,2,3,4,6,7,9]1, 2, 3, then the root4, then the right subtree6, 7, 9.
Example 2
- Input
- node = buildTree().leftout = []
- Output
- The same three steps inside the left subtree alone:
[1,2,3]1, then2, then3.
The Code
function buildTree() {
return {
val: 4,
left: { val: 2, left: { val: 1, left: null, right: null }, right: { val: 3, left: null, right: null } },
right: { val: 7, left: { val: 6, left: null, right: null }, right: { val: 9, left: null, right: null } }
};
}
function inorder(node, out) {
if (node === null) return out;
inorder(node.left, out);
out.push(node.val);
inorder(node.right, out);
return out;
}
inorder(buildTree(), []);Done
The first 8 calls, of 16. This one does not fit on a page.
More like this
All binary trees examples (9) →- Max tree depth A node is one deeper than its deepest child.
- Invert a tree Swap every node’s children, all the way down.
- Validate a BST Every node needs a valid range, not just a valid parent.
- Level order (BFS) Process a whole row, collecting the next one as you go.
- Lowest common ancestor Walk down until the two targets fall on opposite sides.
- Tree diameter Each node returns a depth upward while quietly recording a width.