Skip to content

Commit ea5d166

Browse files
committed
Adding Efficient Solution for Problem - 100 - Same Tree
1 parent fd40d33 commit ea5d166

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

Same_Tree/EfficientSolution.py

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
##==================================
2+
## Leetcode
3+
## Student: Vandit Jyotindra Gajjar
4+
## Year: 2020
5+
## Problem: 100
6+
## Problem Name: Same Tree
7+
##===================================
8+
#Given two binary trees, write a function to check if they are the same or not.
9+
#
10+
#Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
11+
#
12+
#Example 1:
13+
#
14+
#Input: 1 1
15+
# / \ / \
16+
# 2 3 2 3
17+
#
18+
# [1,2,3], [1,2,3]
19+
#
20+
#Output: true
21+
#Example 2:
22+
#
23+
#Input: 1 1
24+
# / \
25+
# 2 2
26+
#
27+
# [1,2], [1,null,2]
28+
#
29+
#Output: false
30+
#Example 3:
31+
#
32+
#Input: 1 1
33+
# / \ / \
34+
# 2 1 1 2
35+
#
36+
# [1,2,1], [1,1,2]
37+
#
38+
#Output: false
39+
class Solution:
40+
def isSameTree(self, p, q):
41+
if p is None and q is None: #Condition-check: If p and q both are empty
42+
return True #We return true
43+
if p is not None and q is None: #Condition-check: If q is empty, while p is not
44+
return False #We return false
45+
if p is None and q is not None: #Condition-check: If p is empty, while q is not
46+
return False #We return false
47+
if p.val != q.val: #Condition-check: If p's val and q's val is not same
48+
return False #We return false
49+
sameLeft = self.isSameTree(p.left, q.left) #Initialize sameLeft by using helper method to check True or False for left subtree
50+
sameRight = self.isSameTree(p.right, q.right) #Initialize sameRight by using helper method to check Tree or False for right subtree
51+
return sameLeft and sameRight #We return True or False if neither of is same or not the same respectively

0 commit comments

Comments
 (0)