-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path100_SameTree.py
59 lines (53 loc) · 1.98 KB
/
100_SameTree.py
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# https://leetcode.com/problems/same-tree/
# 2021 12.07
# 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: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
# # v1 copied recursion
# if p==None and q==None:
# return True
# if p and q:
# if p.val==q.val:
# return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
# else:
# return False
# else :
# return False
# # v1.1 copied recursion more clear
# if not p and not q: # p and q are both None
# return True
# if not p or not q: # one of p and q is None
# return False
# if p.val!=q.val:
# return False
# return self.isSameTree(p.left,q.left) and self.isSameTree(p.right , q.right)
# v2 copied iteretive non-recursive using stack, clear and brilliant
stack=[(p,q)]
while stack:
x,y=stack.pop()
if not x and not y:
continue
if not (x and y):
return False
if x and y:
if x.val==y.val:
stack.append((x.left,y.left))
stack.append((x.right,y.right))
else:
return False
return True
# # v3 Stefan Pochmann
# if p and q:
# return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
# return p is q
# # v3.1 Stefan Pochmann
# def t(n):
# return n and (n.val, t(n.left), t(n.right))
# return t(p) == t(q)
# # v3.2 sick oneliner by Stefan Pochmann
# return p and q and p.val == q.val and all(map(self.isSameTree, (p.left, p.right), (q.left, q.right))) or p is q