Skip to content

Commit 4707ef2

Browse files
authored
feat: 1372. Longest ZigZag Path in a Binary Tree (#42)
1 parent 5cd03a5 commit 4707ef2

3 files changed

Lines changed: 39 additions & 0 deletions

File tree

src/binary_tree/dfs/longest_zigzag_path_in_a_binary_tree/__init__.py

Whitespace-only changes.
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
from typing import Optional
2+
from structures import TreeNode
3+
4+
5+
class Solution:
6+
def dfs(
7+
self, root: Optional[TreeNode], prev_direction: str, cur_length: int
8+
) -> int:
9+
if root is None:
10+
return cur_length - 1
11+
if prev_direction == "left":
12+
right_length = self.dfs(root.right, "right", cur_length + 1)
13+
left_length = self.dfs(root.left, "left", 1)
14+
else:
15+
right_length = self.dfs(root.right, "right", 1)
16+
left_length = self.dfs(root.left, "left", cur_length + 1)
17+
return max(left_length, right_length)
18+
19+
def longestZigZag(self, root: Optional[TreeNode]) -> int:
20+
right_length = self.dfs(root.right, "right", 1)
21+
left_length = self.dfs(root.left, "left", 1)
22+
return max(right_length, left_length)
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import pytest
2+
from src.binary_tree.dfs.longest_zigzag_path_in_a_binary_tree.solution import Solution
3+
from test_utils import TreeBuilder
4+
5+
6+
@pytest.mark.parametrize(
7+
"root, expected",
8+
[
9+
([1, None, 2, 3, 4, None, None, 5, 6, None, 7, None, None, None, 8], 3),
10+
([1, 1, 1, None, 1, None, None, 1, 1, None, 1], 4),
11+
([1], 0),
12+
],
13+
)
14+
def test_max_depth(root, expected):
15+
root = TreeBuilder.from_list(root)
16+
solution = Solution()
17+
assert solution.longestZigZag(root) == expected

0 commit comments

Comments
 (0)