|
| 1 | +# Same Tree |
| 2 | + |
| 3 | +## Problem Description |
| 4 | + |
| 5 | +Given the roots of two binary trees `p` and `q`, write a function to check if they are the same or not. |
| 6 | + |
| 7 | +Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. |
| 8 | + |
| 9 | +**Example 1:** |
| 10 | +Input: `p = [1,2,3], q = [1,2,3]` |
| 11 | +Output: `true` |
| 12 | + |
| 13 | +**Example 2:** |
| 14 | +Input: `p = [1,2], q = [1,null,2]` |
| 15 | +Output: `false` |
| 16 | + |
| 17 | +**Example 3:** |
| 18 | +Input: `p = [1,2,1], q = [1,1,2]` |
| 19 | +Output: `false` |
| 20 | + |
| 21 | +## Solution |
| 22 | + |
| 23 | +```python |
| 24 | +class TreeNode: |
| 25 | + def __init__(self, val=0, left=None, right=None): |
| 26 | + self.val = val |
| 27 | + self.left = left |
| 28 | + self.right = right |
| 29 | + |
| 30 | + |
| 31 | +def is_same_tree(p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: |
| 32 | + """ |
| 33 | + Check if two binary trees are identical in structure and node values. |
| 34 | +
|
| 35 | + :param p: Root node of the first binary tree |
| 36 | + :param q: Root node of the second binary tree |
| 37 | + :return: True if trees are identical, False otherwise |
| 38 | + """ |
| 39 | + if p is None and q is None: |
| 40 | + return True |
| 41 | + elif isinstance(p, int) and isinstance(q, int): |
| 42 | + return p == q |
| 43 | + elif isinstance(p, TreeNode) and isinstance(q, TreeNode): |
| 44 | + if p.val != q.val: |
| 45 | + return False |
| 46 | + return self.is_same_tree(p.left, q.left) and self.is_same_tree(p.right, q.right) |
| 47 | + return False |
| 48 | +``` |
| 49 | + |
| 50 | +* **Time Complexity:** O(n) |
| 51 | +* **Space Complexity:** O(1) |
| 52 | + |
| 53 | +### Explanation of the Solution |
| 54 | + |
| 55 | +This algorithm checks if two binary trees are identical by performing a depth-first comparison: |
| 56 | + |
| 57 | +1. Base Cases: |
| 58 | + * If both nodes are `None` (reached leaf nodes), return `True` |
| 59 | + * If both nodes are integers, compare their values |
| 60 | + * If one is `None` and the other isn't, trees aren't identical (returns `False`) |
| 61 | +2. Tree Comparison: |
| 62 | + * First compares current node values |
| 63 | + * Then recursively compares left subtrees and right subtrees |
| 64 | + * Only returns `True` if all corresponding nodes match in both structure and value |
| 65 | +3. Termination: |
| 66 | + * If any comparison fails at any level, immediately returns `False` |
| 67 | + * Only returns `True` if entire trees are traversed successfully with all nodes matching |
| 68 | + |
| 69 | +The algorithm effectively performs a simultaneous traversal of both trees, comparing nodes at each step. The worst-case scenario occurs when the trees are identical, requiring a full traversal of all nodes. |
0 commit comments