- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem_100.py
More file actions
Latest commit
32 lines (25 loc) · 1.19 KB
/
Copy pathproblem_100.py
File metadata and controls
32 lines (25 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
"""
Problem: https://leetcode.com/problems/same-tree/
Solution: We recursively go to the nodes in both the trees parallely and see if the both the left sub trees and both the right sub trees are same or not.
We also check if the value of the current node is same or not.
If these checks are passed at all the nodes then at the end we declare both the trees as same, Otherwise not.
Time Complexity: O(n) is the time complexity as we traverse all the nodes in both the trees.
Space Complexity: O(1) as we are not creating any additional data structures.
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
classSolution:
defisSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) ->bool:
ifnot(porq):
returnTrue
ifnot(pandq):
returnFalse
leftSubTreeCheck=self.isSameTree(p.left, q.left)
rightSubTreeCheck=self.isSameTree(p.right, q.right)
ifnot (leftSubTreeCheckandrightSubTreeCheckandp.val==q.val):
returnFalse
returnTrue