The problem. Given the root of a binary tree, return the values of its nodes in preorder, inorder and postorder. (On LeetCode these are three separate questions — 144, 94 and 145 — but they are one idea, so they share one lesson.)
root = [1, 2, 3, 4, 5, null, 6]
preorder -> [1, 2, 4, 5, 3, 6]
inorder -> [4, 2, 5, 1, 3, 6]
postorder -> [4, 5, 2, 6, 3, 1]All three are depth-first: go all the way down the left side before the right side. The only difference is when you write down the node — the name says where the root goes: pre = before its subtrees, in = in between them, post = after them.
Each order has a job. Preorder copies or serializes a tree (you meet the root first, so you can rebuild it). Inorder of a binary search tree gives the values in sorted order. Postorder handles children before parents — deleting a tree, or computing sizes and heights.
Picture the recursive walk tracing around the outside of the tree. It passes every node three times: arriving from above, coming back up from the left subtree, and coming back up from the right subtree. Write the value at the first pass for preorder, the second for inorder, the third for postorder.
All three arrays fill in during the same walk — watch which pass writes to which.
The definitions translate straight into code. Only the position of the "visit" line changes:
function preorderTraversal(root, out = []) { if (root === null) return out; out.push(root.val); // root preorderTraversal(root.left, out); // left preorderTraversal(root.right, out); // right return out;} function inorderTraversal(root, out = []) { if (root === null) return out; inorderTraversal(root.left, out); // left out.push(root.val); // root inorderTraversal(root.right, out); // right return out;} function postorderTraversal(root, out = []) { if (root === null) return out; postorderTraversal(root.left, out); // left postorderTraversal(root.right, out); // right out.push(root.val); // root return out;}Time O(n), space O(h) for the call stack — up to O(n) for a skewed tree, which can overflow the call stack on very deep inputs. Interviewers often follow up: now do it without recursion.
function preorderTraversal(root) { const out = []; const stack = root ? [root] : []; while (stack.length > 0) { const node = stack.pop(); out.push(node.val); // visit on the way in if (node.right) stack.push(node.right); if (node.left) stack.push(node.left); // pushed last, popped first } return out;} function inorderTraversal(root) { const out = []; const stack = []; let node = root; while (node !== null || stack.length > 0) { while (node !== null) { // go as far left as possible stack.push(node); node = node.left; } node = stack.pop(); out.push(node.val); // its left side is done: visit node = node.right; // then handle its right side } return out;} function postorderTraversal(root) { const out = []; const stack = root ? [root] : []; while (stack.length > 0) { const node = stack.pop(); out.push(node.val); // root, right, left ... if (node.left) stack.push(node.left); if (node.right) stack.push(node.right); } return out.reverse(); // ... reversed: left, right, root}Time O(n), space O(h) for the stack — the same as recursion, but it can't overflow the call stack, and it's the version interviewers ask for.
Both versions above remember the way back up in a stack. Morris traversal remembers it inside the tree. Before going down into a node's left subtree, find that subtree's rightmost node (the node visited just before this one in inorder) and point its empty right link back up to the current node — a temporary thread. When the walk later arrives through the thread, it knows the left side is finished, removes the thread, and moves right. Every thread is removed, so the tree ends up unchanged.
function inorderTraversal(root) { const out = []; let node = root; while (node !== null) { if (node.left === null) { out.push(node.val); // nothing on the left: visit, go right node = node.right; } else { let pred = node.left; // rightmost node of the left subtree while (pred.right !== null && pred.right !== node) pred = pred.right; if (pred.right === null) { pred.right = node; // 1st arrival: thread back up, go left node = node.left; } else { pred.right = null; // 2nd arrival: remove the thread out.push(node.val); // left side done: visit node = node.right; } } } return out;} function preorderTraversal(root) { const out = []; let node = root; while (node !== null) { if (node.left === null) { out.push(node.val); node = node.right; } else { let pred = node.left; while (pred.right !== null && pred.right !== node) pred = pred.right; if (pred.right === null) { out.push(node.val); // preorder: visit on the 1st arrival pred.right = node; node = node.left; } else { pred.right = null; node = node.right; } } } return out;}Time O(n), space O(1). Finding predecessors walks some edges twice, but every edge is walked at most a constant number of times overall. The catch: the tree is modified during the walk, so it isn't safe if another thread reads the tree at the same time. (A Morris postorder exists too, but it's fiddly; in interviews, the iterative version is the usual answer.)
O(n)Every node is visited once.
O(h)The call stack: up to O(n) for a skewed tree.
O(n)[].[root].[3, 2, null, 1]: preorder 3 2 1, inorder 1 2 3, postorder 1 2 3.[1, null, 2, null, 3]: recursion depth equals n.Every node is pushed and popped once.
O(h)An explicit stack of one path, which can't overflow the call stack.
O(n)Finding predecessors walks each edge a constant number of times.
O(1)It threads through the tree's empty right pointers instead of a stack.