Leetcode 1474 Solution
This article provides solution to leetcode question 1474 (longest-zigzag-path-in-a-binary-tree)
Access this page by simply typing in "lcs 1474" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree
Solution
# 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:
ans = 0
def dfs(node):
nonlocal ans
if not node:
return -1, -1
left_max = dfs(node.left)[1] + 1
right_max = dfs(node.right)[0] + 1
ans = max(ans, left_max, right_max)
return left_max, right_max
dfs(root)
return ans