Same Tree - Complete Solution Guide
Same Tree is LeetCode problem 100, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
Given the roots of two binary trees p and q , write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. Example 1: Input: p = [1,2,3], q = [1,2,3] Output: true Example 2: Input: p = [1,2], q = [1,null,2] Output: false Example 3: Input: p = [1,2,1], q = [1,1,2] Output: false Constraints: The number of nodes in both trees is in the range [0, 100] . -10 4 <= Node.val <= 10 4
Detailed Explanation
This problem challenges us to determine if two given binary trees, `p` and `q`, are fundamentally identical. What does 'identical' mean here? It's not just about having the same set of values, but rather a strict combination of structural congruence and matching node values at every corresponding position. For instance, if `p` has a left child with value 2 and `q` has a left child with value 2, that's a match. But if `p` has a left child and `q` has *no* left child (or a `null` child), they are immediately different, regardless of what other nodes might exist. This is perfectly illustrated by Example 2, where `p = [1,2]` (a root 1 with a left child 2) and `q = [1,null,2]` (a root 1 with a right child 2). Despite having the same values, their structures diverge right after the root, making them unequal.
Solution Approach
The most intuitive and elegant approach for this problem leverages the recursive nature of binary trees themselves, using a Depth-First Search (DFS) strategy. The core idea is to break down the problem: two trees are the same if and only if their current nodes are identical (both null, or both non-null with matching values), AND their left subtrees are identical, AND their right subtrees are identical. The provided solution directly implements this principle. It starts by comparing the roots: if both are null, they are trivially the same. If only one is null, they are structurally different. If both exist but have different values, they are also different. Only if all these checks pass do we recursively apply the *exact same logic* to their left children and their right children. The `and` operator ensures that *both* left and right subproblems must return true for the current subproblem to be considered true, effectively short-circuiting and returning `false` as soon as any mismatch is found anywhere in the tree.
Step-by-Step Algorithm
- Step 1: Check if both `p` and `q` are `null` (or `None`). If so, return `true` (both trees are empty and identical).
- Step 2: Check if either `p` or `q` is `null` (or `None`). If so, return `false` (one tree is empty, the other is not).
- Step 3: Check if the values of the root nodes (`p.val` and `q.val`) are different. If so, return `false`.
- Step 4: Recursively call `isSameTree` on the left subtrees (`p.left` and `q.left`) and the right subtrees (`p.right` and `q.right`).
- Step 5: Return `true` only if both recursive calls in step 4 return `true`; otherwise, return `false`.
Key Insights
- The problem's definition of 'sameness' is inherently recursive: two trees are identical if their roots match AND their corresponding subtrees recursively match. This makes a recursive DFS traversal the most natural and clean algorithmic fit.
- Handling `null` (or `None`) nodes is paramount for establishing structural identity. The solution carefully differentiates between both nodes being `null` (structurally identical empty branches), and one being `null` while the other is not (an immediate structural mismatch, e.g., `p` has a left child but `q` doesn't).
- Early exit conditions (short-circuiting) are crucial for efficiency. As soon as any structural difference (one node is `null`, the other isn't) or value mismatch is detected at any level, the function immediately returns `False`. There's no need to continue traversing deeper into branches that are already confirmed to be different.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(log n)
Topics
This problem involves: Tree, Depth-First Search, Breadth-First Search, Binary Tree.
Companies
Asked at: Adobe, Amazon, Apple, Bloomberg, Flipkart, Google, LinkedIn, Meta, Microsoft, Yahoo, tcs.