Skip to content

Commit a3b5093

Browse files
committed
added 0100_same_tree.py
1 parent 17400cb commit a3b5093

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

problems/easy/0100_same_tree.py

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
"""
2+
Given the roots of two binary trees p and q, write a function to
3+
check if they are the same or not.
4+
5+
Two binary trees are considered the same if they are structurally
6+
identical, and the nodes have the same value.
7+
8+
Example 1:
9+
Input: p = [1,2,3], q = [1,2,3]
10+
Output: true
11+
12+
Example 2:
13+
Input: p = [1,2], q = [1,null,2]
14+
Output: false
15+
16+
Example 3:
17+
Input: p = [1,2,1], q = [1,1,2]
18+
Output: false
19+
20+
Constraints:
21+
* The number of nodes in both trees is in the range [0, 100]
22+
* -10^4 <= Node.val <= 10^4
23+
"""
24+
25+
class Solution:
26+
# O(2^n) solution, iterative
27+
#def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
28+
# if p is None and q is None:
29+
# return True
30+
#
31+
# if p is None or q is None:
32+
# return False
33+
#
34+
# stack_p = [p.right, p.left, p]
35+
# stack_q = [q.right, q.left, q]
36+
# while len(stack_p) and len(stack_q):
37+
# p = stack_p.pop()
38+
# q = stack_q.pop()
39+
#
40+
# if p is None and q is None:
41+
# return True
42+
#
43+
# if p.val != q.val:
44+
# return False
45+
#
46+
# # False, if one has a left node and the other one does not
47+
# if (p.left is None) ^ (q.left is None):
48+
# return False
49+
#
50+
# # False, if one has a right node and the other one does not
51+
# if (p.right is None) ^ (q.right is None):
52+
# return False
53+
#
54+
# if not p.right is None:
55+
# stack_p.append(p.right)
56+
# stack_q.append(q.right)
57+
#
58+
# if not p.left is None:
59+
# stack_p.append(p.left)
60+
# stack_q.append(q.left)
61+
#
62+
# return len(stack_p) == len(stack_q)
63+
64+
# O(2^n) solution, recursive one
65+
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
66+
if (p is None) ^ (q is None):
67+
return False
68+
69+
if p is None and q is None:
70+
return True
71+
72+
if p.val != q.val:
73+
return False
74+
75+
if self.isSameTree(p.left, q.left):
76+
return self.isSameTree(p.right, q.right)
77+
78+
return False

0 commit comments

Comments
 (0)