LeetCode75-1372-ZigZag

🧠 Summary of Thoughts

ZigZag = alternate walking left and right

  1. Use Depth-First Search (DFS) to traverse the tree recursively.
  2. Track the current path length separately for left and right directions.
  3. At each node:
  • Update the maximum ZigZag length.
  • Recurse to the left child with the path continuing from the right direction.
  • Recurse to the right child with the path continuing from the left direction.
  1. Maintain a global or class-level variable to store the maximum path length found.

✅ Code(Java)

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int max = 0;
public int longestZigZag(TreeNode root) {
dfs(root, 0, 0);
return max;
}
private void dfs(TreeNode node, int leftLen, int rightLen) {
if (node == null) {
return;
}
max = Math.max(max, Math.max(leftLen, rightLen));
dfs(node.left, rightLen + 1, 0);
dfs(node.right, 0, leftLen + 1);
}
}

LeetCode75-1372-ZigZag
https://powersixxx.github.io/leetcode-blog/2026/02/28/LeetCode75-1372-ZigZag/
作者
Baowen Liu
发布于
2026年2月28日
许可协议