1372. Longest ZigZag Path in a Binary Tree
Problem
A zigzag path starts at any node, picks a direction (left or right), and alternates direction at every step down. Return the length (in edges) of the longest zigzag path.
Example: [1,1,1,null,1,null,null,1,1,null,1] → 4
Constraints: up to 5·10⁴ nodes.
For every node compute two values: the longest zigzag starting here going left (= 1 + the left child's "going right" value) and going right (= 1 + the right child's "going left"). A missing child contributes −1 so the step to it counts 0. The answer is the maximum over all nodes.
Complexity: O(n).
class Solution:
def longestZigZag(self, root: Optional[TreeNode]) -> int:
best = 0
def dfs(node): # -> (zigzag length going left, going right), in edges
nonlocal best
if not node:
return -1, -1
left = dfs(node.left)[1] + 1
right = dfs(node.right)[0] + 1
best = max(best, left, right)
return left, right
dfs(root)
return best
assert Solution().longestZigZag(make_tree([1, None, 1, 1, 1, None, None, 1, 1, None, 1, None, None, None, 1])) == 3
assert Solution().longestZigZag(make_tree([1, 1, 1, None, 1, None, None, 1, 1, None, 1])) == 4
assert Solution().longestZigZag(make_tree([1])) == 0
class Solution {
private int best = 0;
public int longestZigZag(TreeNode root) {
dfs(root);
return best;
}
private int[] dfs(TreeNode n) { // {going left, going right}
if (n == null) return new int[]{-1, -1};
int left = dfs(n.left)[1] + 1, right = dfs(n.right)[0] + 1;
best = Math.max(best, Math.max(left, right));
return new int[]{left, right};
}
}
func longestZigZag(root *TreeNode) int {
best := 0
var dfs func(*TreeNode) (int, int) // zigzag length (in edges) starting with a left / right step
dfs = func(node *TreeNode) (int, int) {
if node == nil {
return -1, -1
}
_, lr := dfs(node.Left)
rl, _ := dfs(node.Right)
left, right := lr+1, rl+1
best = max(best, left, right)
return left, right
}
dfs(root)
return best
}