DFS/BFS Traversals & Path Problems
Click "Start" to begin tree traversal
Easy
Return inorder traversal of tree (iterative & recursive).
Solve on LeetCode →// Inorder: Left → Root → Right
function inorder(root) {
if (!root) return;
inorder(root.left);
visit(root);
inorder(root.right);
}
// Preorder: Root → Left → Right
function preorder(root) {
if (!root) return;
visit(root);
preorder(root.left);
preorder(root.right);
}
// Postorder: Left → Right → Root
function postorder(root) {
if (!root) return;
postorder(root.left);
postorder(root.right);
visit(root);
}
function levelOrder(root) {
if (!root) return [];
const result = [];
const queue = [root];
while (queue.length > 0) {
const levelSize = queue.length;
const currentLevel = [];
for (let i = 0; i < levelSize; i++) {
const node = queue.shift();
currentLevel.push(node.val);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
result.push(currentLevel);
}
return result;
}
function hasPathSum(root, targetSum) {
if (!root) return false;
// Leaf node
if (!root.left && !root.right) {
return root.val === targetSum;
}
// Recurse with reduced sum
const remaining = targetSum - root.val;
return hasPathSum(root.left, remaining) ||
hasPathSum(root.right, remaining);
}