diff --git a/src/binary_tree/dfs/longest_zigzag_path_in_a_binary_tree/__init__.py b/src/binary_tree/dfs/longest_zigzag_path_in_a_binary_tree/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/binary_tree/dfs/longest_zigzag_path_in_a_binary_tree/solution.py b/src/binary_tree/dfs/longest_zigzag_path_in_a_binary_tree/solution.py new file mode 100644 index 0000000..69e1033 --- /dev/null +++ b/src/binary_tree/dfs/longest_zigzag_path_in_a_binary_tree/solution.py @@ -0,0 +1,22 @@ +from typing import Optional +from structures import TreeNode + + +class Solution: + def dfs( + self, root: Optional[TreeNode], prev_direction: str, cur_length: int + ) -> int: + if root is None: + return cur_length - 1 + if prev_direction == "left": + right_length = self.dfs(root.right, "right", cur_length + 1) + left_length = self.dfs(root.left, "left", 1) + else: + right_length = self.dfs(root.right, "right", 1) + left_length = self.dfs(root.left, "left", cur_length + 1) + return max(left_length, right_length) + + def longestZigZag(self, root: Optional[TreeNode]) -> int: + right_length = self.dfs(root.right, "right", 1) + left_length = self.dfs(root.left, "left", 1) + return max(right_length, left_length) diff --git a/tests/test_longest_zigzag_path_in_a_binary_tree.py b/tests/test_longest_zigzag_path_in_a_binary_tree.py new file mode 100644 index 0000000..4e7c4ab --- /dev/null +++ b/tests/test_longest_zigzag_path_in_a_binary_tree.py @@ -0,0 +1,17 @@ +import pytest +from src.binary_tree.dfs.longest_zigzag_path_in_a_binary_tree.solution import Solution +from test_utils import TreeBuilder + + +@pytest.mark.parametrize( + "root, expected", + [ + ([1, None, 2, 3, 4, None, None, 5, 6, None, 7, None, None, None, 8], 3), + ([1, 1, 1, None, 1, None, None, 1, 1, None, 1], 4), + ([1], 0), + ], +) +def test_max_depth(root, expected): + root = TreeBuilder.from_list(root) + solution = Solution() + assert solution.longestZigZag(root) == expected