[LeetCode] Longest ZigZag Path in a Binary Tree

1372. Longest ZigZag Path in a Binary Tree

You are given the root of a binary tree.

A ZigZag path for a binary tree is defined as follow:

  • Choose any node in the binary tree and a direction (right or left).
  • If the current direction is right, move to the right child of the current node; otherwise, move to the left child.
  • Change the direction from right to left or from left to right.
  • Repeat the second and third steps until you can’t move in the tree.

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.

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.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
int res = 0;
int helper(TreeNode* node, bool amIRight) {
if(!node) return 0;
if(amIRight) {
res = max(res, 1 + helper(node->right, true));
return 1 + helper(node->left, false);
} else {
res = max(res, 1 + helper(node->left, false));
return 1 + helper(node->right, true);
}
}
public:
int longestZigZag(TreeNode* root) {
res = max(res, 1 + helper(root->left, false));
res = max(res, 1 + helper(root->right, true));
return res - 1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/13/PS/LeetCode/longest-zigzag-path-in-a-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.