Skip to main content

Depth First Search

This technique uses recursion or iterative approach using stack to keep track of all the previous (parent) nodes while traversing trees in a depth-first search manner.

How to Identify

  • Data Structure Involves: Tree, Graph
  • Question Type: Traverse a tree with in-order, preorder, or postorder.

Example

Recursive

preOrderTraversal.ts
import {TreeNode} from "./TreeNode"
function preOrderTraversal(root: TreeNode | null, result: number[]) {
// base case
if(root === null) return

// recursive case
result.push(root.val) // <== preorder
preOrderTraversal(root.left, result)
preOrderTraversal(root.right, result)
}

Iterative

preOrderTraversal.ts
import {TreeNode} from "./TreeNode"
function dfsPreOrder(root: TreeNode | null): number[] {
if(root === null) return[]
const stack = [root]
const order = []

while(stack.length > 0) {
const currentNode = stack.pop()
order.push(currentNode.val)

if(currentNode.right) stack.push(currentNode.right)
if(currentNode.left) stack.push(currentNode.left)
}

return order
}
ProblemsDifficulty
1Maximum Depth of Binary TreeEasy
2Same TreeEasy
3Invert Binary TreeEasy
4Subtree of Another TreeEasy
5Lowest Common Ancestor of BSTEasy
6Construct Binary Tree from Preorder and Inorder TraversalMedium
7Validate Binary Search TreeMedium
8Kth Smallest Element in a BSTMedium
9Binary Tree Maximum Path SumHard