Binary Tree DFS
Watch the walkthrough
Open on InstagramProblem
Visit a binary tree in preorder, inorder, and postorder.
Approach and revision checks
Preorder is node-left-right; inorder is left-node-right; postorder is left-right-node. Each visits n nodes in O(n) time and uses O(h) stack space for height h. The copied PostorderTraverse function is correctly postorder even though its preceding comment says Inorder. These functions log values rather than return an array. Test null, a leaf, and a skewed tree.
Original repository source
Copied from the supplied local DSA-Series checkout; code and comments are preserved. Run alternative definitions separately when comparing approaches.
7-tree-dfs.js
// Tree Structure Definition
function TreeNode(val = 0, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
// Preorder
function preorderTraverse(node) {
if (!node) return;
console.log(node.val);
preorderTraverse(node.left);
preorderTraverse(node.right);
}
// Inorder
function InorderTraverse(node) {
if (!node) return;
InorderTraverse(node.left);
console.log(node.val);
InorderTraverse(node.right);
}
// Inorder
function PostorderTraverse(node) {
if (!node) return;
PostorderTraverse(node.left);
PostorderTraverse(node.right);
console.log(node.val);
}