-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathlongest-zigzag-path-in-a-binary-tree.py
41 lines (34 loc) · 1.14 KB
/
longest-zigzag-path-in-a-binary-tree.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
from typing import Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def longestZigZag(self, root: TreeNode) -> int:
def dfs(node: TreeNode, direction: Optional[bool], count: int, max_count: int):
# direction: True - left, False - right, None - root node
max_count = max(max_count, count)
if node.left:
max_count = max(
max_count,
dfs(
node.left,
True,
1 if direction == True else count + 1,
max_count,
),
)
if node.right:
max_count = max(
max_count,
dfs(
node.right,
False,
1 if direction == False else count + 1,
max_count,
),
)
return max_count
return dfs(root, None, 0, 0)