-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathm1372.py
52 lines (47 loc) · 1.59 KB
/
m1372.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
# 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 longestZigZag(self, root: Optional[TreeNode]) -> int:
goneLeft = set()
goneRight = set()
maxx = 0
toVisit = [root]
while toVisit :
curr = toVisit.pop()
if curr.right and curr not in goneRight :
cnt = 0
direction = True
temp = curr
while temp :
if direction :
goneRight.add(temp)
temp = temp.right
else :
goneLeft.add(temp)
temp = temp.left
direction = not direction
cnt += 1
maxx = max(maxx, cnt - 1)
if curr.left and curr not in goneLeft :
cnt = 0
direction = False
temp = curr
while temp :
if direction :
goneRight.add(temp)
temp = temp.right
else :
goneLeft.add(temp)
temp = temp.left
direction = not direction
cnt += 1
maxx = max(maxx, cnt - 1)
if curr.right :
toVisit.append(curr.right)
if curr.left :
toVisit.append(curr.left)
return maxx