Coding Flashcards
(3 cards)
DFS
void dfsRecursive(TreeNode node) {
if (node == null) {
return; // Base case: nothing to explore
}
// Process the current node (e.g., print its value) System.out.print(node.val + " "); // Recursively visit each child for (TreeNode child : node.children) { dfsRecursive(child); } }
Iterative:
- push children on to stack
- be mindful of order of processing (potentially need to push children onto stack in reverse order)
- be mindful of checking for visited (may need to remove items from visited set)
Processing tree order
Pre-order: Process the current node before visiting its children (as shown in the examples above).
In-order: Process the left child, then the current node, then the right child (most common for Binary Search Trees). This doesn’t directly apply to general trees with multiple children in the same way.
Post-order: Process all children before processing the current node.