Skip to content

Commit 2aa9e43

Browse files
committed
Add same tree
1 parent 3a8d1ed commit 2aa9e43

File tree

2 files changed

+102
-0
lines changed

2 files changed

+102
-0
lines changed

binary-tree/100_Same_Tree/README.md

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
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.

binary-tree/100_Same_Tree/solution.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
from typing import Optional
2+
3+
# Definition for a binary tree node.
4+
class TreeNode:
5+
def __init__(self, val=0, left=None, right=None):
6+
self.val = val
7+
self.left = left
8+
self.right = right
9+
10+
11+
def is_same_tree(p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
12+
"""
13+
Check if two binary trees are identical in structure and node values.
14+
15+
:param p: Root node of the first binary tree
16+
:param q: Root node of the second binary tree
17+
:return: True if trees are identical, False otherwise
18+
"""
19+
if p is None and q is None:
20+
return True
21+
elif isinstance(p, int) and isinstance(q, int):
22+
return p == q
23+
elif isinstance(p, TreeNode) and isinstance(q, TreeNode):
24+
if p.val != q.val:
25+
return False
26+
return self.is_same_tree(p.left, q.left) and self.is_same_tree(p.right, q.right)
27+
return False
28+
29+
30+
31+
assert is_same_tree(p=TreeNode(1, 2, 3), q=TreeNode(1, 2, 3)) == True, 'Test 1 Failed'
32+
assert is_same_tree(p=TreeNode(1, 2), q=TreeNode(1, None, 2)) == False, 'Test 2 Failed'
33+
assert is_same_tree(p=TreeNode(1, 2, 1), q=TreeNode(1, 1, 2)) == False, 'Test 3 Failed'

0 commit comments

Comments
 (0)