You are given the root of a binary tree.
A ZigZag path for a binary tree is defined as follow:
Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0).
Return the longest ZigZag path contained in that tree.
?
Input root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1]
Output 3
Explanation: Longest ZigZag path in blue nodes (right -> left -> right).
Input root = [1,1,1,null,1,null,null,1,1,null,1]
Output 4
Explanation: Longest ZigZag path in blue nodes (left -> right -> left -> right).
Input root = [1]
Output 0
From: LeetCode
Link: 1372. Longest ZigZag Path in a Binary Tree
Global Maximum Length: We keep a global variable or a pointer reference (longest) to store the maximum length of any ZigZag path we find in the tree.
Recursive Helper Function (updateZigZag): The helper function is designed to be called recursively for each node in the tree, and it performs the following actions:
Two Initial Calls: The longestZigZag function initializes the maximum length to zero and then makes two initial calls to the helper function: one assuming the ZigZag path starts by going left from the root, and another assuming it starts by going right.
Returning the Result: After the entire tree has been traversed, the longest variable will hold the length of the longest ZigZag path found in the tree. This value is then returned.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
// Helper function to update the longest zigzag path
void updateZigZag(struct TreeNode* node, int direction, int length, int* longest) {
if (!node) return;
// Update the longest length found so far
*longest = length > *longest ? length : *longest;
// Continue in the ZigZag path
if (direction == 0) {
updateZigZag(node->left, 1, length + 1, longest); // Change direction to right
updateZigZag(node->right, 0, 1, longest); // Reset length if changing direction
} else {
updateZigZag(node->right, 0, length + 1, longest); // Change direction to left
updateZigZag(node->left, 1, 1, longest); // Reset length if changing direction
}
}
int longestZigZag(struct TreeNode* root) {
int longest = 0;
updateZigZag(root, 0, 0, &longest); // Start with direction as left (0)
updateZigZag(root, 1, 0, &longest); // Start with direction as right (1)
return longest;
}