From a3fca26cdde989037a6df54eefa6c4bee4228190 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Wed, 21 Aug 2024 15:39:10 +0200 Subject: [PATCH] =?UTF-8?q?cs:=20add=20=C2=AB1372.=20Longest=20ZigZag=20Pa?= =?UTF-8?q?th=20in=20a=20Binary=20Tree=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- cs/longest-zigzag-path-in-a-binary-tree.cs | 41 ++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 cs/longest-zigzag-path-in-a-binary-tree.cs diff --git a/cs/longest-zigzag-path-in-a-binary-tree.cs b/cs/longest-zigzag-path-in-a-binary-tree.cs new file mode 100644 index 0000000..2d9dcb6 --- /dev/null +++ b/cs/longest-zigzag-path-in-a-binary-tree.cs @@ -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) + ); +}