Untitled
class Solution { private int maxZigZag = 0; public int longestZigZag(TreeNode root) { dfs(root, true, 0); // Initialize DFS for the left direction return maxZigZag; } private void dfs(TreeNode node, boolean isLeft, int length) { if (node == null) return; // Update the global maximum ZigZag length maxZigZag = Math.max(maxZigZag, length); if (isLeft) { // Moving left: Continue with the left child, reset with the right child dfs(node.left, false, length + 1); dfs(node.right, true, 1); } else { // Moving right: Continue with the right child, reset with the left child dfs(node.right, true, length + 1); dfs(node.left, false, 1); } } }
Leave a Comment