Recursive DFS Solution for Same Tree Problem on LeetCode

✅ Solved LeetCode: Same Tree (100) — Recursive DFS Approach Implemented a clean recursive solution in JavaScript using a structural comparison strategy. Approach: - If both nodes p and q are null, return true. - If only one of them is null, return false. - Otherwise: - Check if p.val === q.val. - Recursively compare: - p.left with q.left - p.right with q.right - Return the combined result of value equality and both subtree comparisons. This approach ensures both structure and node values are identical at every level of the tree. Time Complexity: O(n) — each node is visited once Space Complexity: O(h) — recursion stack space (where h is tree height) A straightforward and elegant recursive pattern for tree comparison problems!

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories