2Brute2Best
🔥0
01

Traversal / comparison (Tree DFS Sub-pattern)

Visit every node in a fixed order, or walk two trees side by side and compare them node by node.

Signals in the problem statement
  • ›

    "maximum depth"

  • ›

    "inorder / preorder / postorder traversal"

  • ›

    "same tree", "mirror of itself", "subtree of another tree"

What makes it different

Maximum Depth is the first bottom-up answer: 1 + max(left, right). Inorder Traversal is about the order itself: recursion, then an explicit stack, then Morris for O(1) space. Same Tree walks two trees together and fails on the first mismatch. Symmetric Tree walks the tree against its own mirror: left's left with right's right. Subtree of Another Tree runs Same Tree from every node (O(m·n)), or serializes both with null markers and searches the string.

Questions

ordered from “learn the idea” to “recognise it without help”
  1. 1
    Maximum Depth of Binary Tree
    Basic Anchor·LeetCode #104
    Easy
  2. 2
    Binary Tree Inorder Traversal
    Basic Reinforcement·LeetCode #94
    Easy
  3. 3
    Same Tree
    Slight Variation·LeetCode #100
    Easy
  4. 4
    Symmetric Tree
    Medium·LeetCode #101
    Easy
  5. 5
    Subtree of Another Tree
    Pattern Transfer·LeetCode #572
    Easy

Template

traversal-template.cpp
// Recursive DFS: the three orders differ only in WHERE you handle the node.
void dfs(TreeNode* node, vector<int>& out) {
    if (!node) return;
    // preorder:  out.push_back(node->val);   (node before its children)
    dfs(node->left, out);
    out.push_back(node->val);                 // inorder: between the two children
    dfs(node->right, out);
    // postorder: out.push_back(node->val);  (node after both children)
}

// Iterative inorder with your own stack: go left as far as possible, then visit, then go right.
vector<int> inorderIterative(TreeNode* root) {
    vector<int> out;
    stack<TreeNode*> st;
    TreeNode* cur = root;
    while (cur || !st.empty()) {
        while (cur) { st.push(cur); cur = cur->left; }   // everything on the way down waits its turn
        cur = st.top(); st.pop();
        out.push_back(cur->val);                         // its whole left side is already done
        cur = cur->right;
    }
    return out;
}

// Two trees at once: compare the pair, then recurse on matching pairs of children.
bool isSameTree(TreeNode* p, TreeNode* q) {
    if (!p || !q) return p == q;                         // both null → same; one null → different
    return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
Remember this · Tree DFS
Trigger
Paths, heights, diameters, validating structure, ancestors, anything "for every subtree".
Think
If my left and right children already gave me their answers, how do I build mine?
Key question
What does my recursive function return, and what do I pass down?