mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
cs: add «1372. Longest ZigZag Path in a Binary Tree»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
34b86138ef
commit
a3fca26cdd
1 changed files with 41 additions and 0 deletions
41
cs/longest-zigzag-path-in-a-binary-tree.cs
Normal file
41
cs/longest-zigzag-path-in-a-binary-tree.cs
Normal file
|
@ -0,0 +1,41 @@
|
||||||
|
public class Solution {
|
||||||
|
public enum Direction {
|
||||||
|
Left,
|
||||||
|
Right,
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Direction Next(Direction d) => d switch {
|
||||||
|
Direction.Left => Direction.Right,
|
||||||
|
Direction.Right => Direction.Left,
|
||||||
|
_ => throw new ArgumentException("Invalid direction")
|
||||||
|
};
|
||||||
|
|
||||||
|
private static TreeNode? Get(Direction d, TreeNode n) => d switch {
|
||||||
|
Direction.Left => n.left,
|
||||||
|
Direction.Right => n.right,
|
||||||
|
_ => throw new ArgumentException("Invalid direction")
|
||||||
|
};
|
||||||
|
|
||||||
|
private int LongestZigZag(TreeNode node, int steps, Direction direction) {
|
||||||
|
if (node == null) {
|
||||||
|
return steps;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Current path
|
||||||
|
var maxSteps = steps;
|
||||||
|
|
||||||
|
// Switching direction
|
||||||
|
maxSteps = Math.Max(maxSteps, LongestZigZag(Get(direction, node), steps + 1, Next(direction)));
|
||||||
|
|
||||||
|
// Starting new path
|
||||||
|
maxSteps = Math.Max(maxSteps, LongestZigZag(Get(Next(direction), node), 0, direction));
|
||||||
|
|
||||||
|
return maxSteps;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int LongestZigZag(TreeNode root)
|
||||||
|
=> Math.Max(
|
||||||
|
LongestZigZag(root, -1, Direction.Left),
|
||||||
|
LongestZigZag(root, -1, Direction.Right)
|
||||||
|
);
|
||||||
|
}
|
Loading…
Reference in a new issue