Concepts

Binary-tree traversal

Try the free JavaScript compiler

Inorder traversal of a binary tree; preorder emits before both child calls, postorder after both. Runtime and stack cost depend on node count and height.

Formal Syntax & Structure

javascript syntaxjavascript
visit(left); emit(node); visit(right);

Working Example

Example Snippetjavascript
const tree={v:2,left:{v:5,left:null,right:null},right:{v:1,left:null,right:null}};const pre=[],inside=[];function visit(n){if(!n)return;pre.push(n.v);visit(n.left);inside.push(n.v);visit(n.right);}visit(tree);console.log(JSON.stringify(pre),JSON.stringify(inside));
JavaScript Reference