Skip to content

Instantly share code, notes, and snippets.

@cfrank
Last active June 5, 2023 17:36
Show Gist options
  • Save cfrank/b0f3681ae6790c09fe0c902270567d79 to your computer and use it in GitHub Desktop.
Save cfrank/b0f3681ae6790c09fe0c902270567d79 to your computer and use it in GitHub Desktop.
1372. Longest ZigZag Path in a Binary Tree
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
enum Direction {
RIGHT,
LEFT,
};
function longestZigZag(root: TreeNode | null): number {
const findLongestZigZag = (node: TreeNode | null, startingDirection: Direction, depth: number) => {
if (!node) {
return depth;
}
const right = findLongestZigZag(node.right, Direction.RIGHT, startingDirection === Direction.LEFT ? depth + 1 : 0);
const left = findLongestZigZag(node.left, Direction.LEFT, startingDirection === Direction.RIGHT ? depth + 1 : 0);
return Math.max(right, left);
}
const right = findLongestZigZag(root.right, Direction.RIGHT, 0);
const left = findLongestZigZag(root.left, Direction.LEFT, 0);
return Math.max(right, left);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment