LeetCode 1372. Longest ZigZag Path in a Binary Tree
Given a binary tree root, 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 then move to the right child of the current node otherwise move to the left child.
Change the direction from right to left or right to left.
Repeat the second and third step 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(the length) contained in that tree.
idea:
No idea. when I meet this kind of problem, the first phrase came to my mind is: what the hell? Some lunatic came up with this kind of problem, and for what? for fun?
I have no clue of how to solve problems like this.
but I have a general idea: we get every path iterated and maintain the longest path.
but how can we do the zig zag and count the length at the same time. we need to maintain that longest number as the global var.
class Solution {
private int max = 0;
public int longestZigZag(TreeNode root) {
if (root == null) return -1;
helper(root.right, 1, true); //start from both side
helper(root.left, 1, false);
return max;
}
private void helper(TreeNode root, int step, boolean isRight) {
if (root == null) return;
max = Math.max(max, step);
if (isRight) { //current is right way and the next need to be left way
helper(root.left, step + 1, false); //if this is not going
helper(root.right, 1, true); //try to restart from another way, step reset to 1d
} else {
helper(root.right, step + 1, true);
helper(root.left, 1, false);
}
}
}

浙公网安备 33010602011771号