-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsame_tree.py
More file actions
41 lines (30 loc) · 1.05 KB
/
same_tree.py
File metadata and controls
41 lines (30 loc) · 1.05 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
33
34
35
36
37
38
39
40
41
# 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
class Solution:
def isSameTree(self, p, q):
if not p and not q:
return True
if (p and not q) or (not p and q):
return False
if p.val != q.val:
return False
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right ,q.right)
# Time Complexity: O(n)
# Space Complexity: O(h)
def isSameTree(self, p, q):
stack = [(p, q)]
while stack:
p, q = stack.pop()
if not p and not q:
continue
if (p and not q) or (not p and q):
return False
if p.val != q.val:
return False
stack.append((p.left, q.left)) if p and q else None
stack.append((p.right, q.right)) if p and q else None
return True