100. Same Tree
## description
## 100. Same Tree
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:
1Input: p = [1,2,3], q = [1,2,3]
2Output: trueExample 2:
1Input: p = [1,2], q = [1,null,2]
2Output: falseExample 3:
1Input: p = [1,2,1], q = [1,1,2]
2Output: false- –The number of nodes in both trees is in the range [0, 100].
- –-104 <= Node.val <= 104
Constraints:
## notes
### Intuition
Two trees are identical if their structure and node values match exactly. By traversing both trees simultaneously, we can compare nodes at each position.
### Implementation
Use recursive DFS to check both trees in parallel. The base case is when both p and q are null—this means we've reached the end of both subtrees successfully, so return true. If both nodes exist and their values match, recursively verify that the left subtrees are the same AND the right subtrees are the same. If any of these conditions fail, return false.
### Edge-cases
No special edge cases beyond the base conditions. The recursion naturally handles trees of different shapes or sizes since a mismatch (one null, one not) will return false.
- –Time: O(n) — visit each node once
- –Space: O(h) — recursion stack depth equals tree height
### Complexity
## solution
1from typing import Optional
2from lcutils import TreeNode
3
4# Definition for a binary tree node.
5# class TreeNode:
6# def __init__(self, val=0, left=None, right=None):
7# self.val = val
8# self.left = left
9# self.right = right
10class Solution:
11 def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
12 if not p and not q:
13 return True
14 if p and q and p.val == q.val:
15 return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
16 else:
17 return False
18
19
20
21
22if __name__ == "__main__":
23 # Include one-off tests here or debugging logic that can be run by running this file
24 # e.g. print(solution.two_sum([1, 2, 3, 4], 3))
25 solution = Solution()
26