|
| 1 | +/** |
| 2 | + * 1372. Longest ZigZag Path in a Binary Tree |
| 3 | + * https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given the root of a binary tree. |
| 7 | + * |
| 8 | + * A ZigZag path for a binary tree is defined as follow: |
| 9 | + * - Choose any node in the binary tree and a direction (right or left). |
| 10 | + * - If the current direction is right, move to the right child of the current node; |
| 11 | + * otherwise, move to the left child. |
| 12 | + * - Change the direction from right to left or from left to right. |
| 13 | + * - Repeat the second and third steps until you can't move in the tree. |
| 14 | + * |
| 15 | + * Zigzag length is defined as the number of nodes visited - 1. (A single node has a |
| 16 | + * length of 0). |
| 17 | + * |
| 18 | + * Return the longest ZigZag path contained in that tree. |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * Definition for a binary tree node. |
| 23 | + * function TreeNode(val, left, right) { |
| 24 | + * this.val = (val===undefined ? 0 : val) |
| 25 | + * this.left = (left===undefined ? null : left) |
| 26 | + * this.right = (right===undefined ? null : right) |
| 27 | + * } |
| 28 | + */ |
| 29 | +/** |
| 30 | + * @param {TreeNode} root |
| 31 | + * @return {number} |
| 32 | + */ |
| 33 | +var longestZigZag = function(root) { |
| 34 | + let result = 0; |
| 35 | + |
| 36 | + dfs(root, true, 0); |
| 37 | + dfs(root, false, 0); |
| 38 | + |
| 39 | + return result; |
| 40 | + |
| 41 | + function dfs(node, isLeft, total) { |
| 42 | + if (!node) return; |
| 43 | + result = Math.max(result, total); |
| 44 | + dfs(node.left, true, isLeft ? 1 : total + 1); |
| 45 | + dfs(node.right, false, isLeft ? total + 1 : 1); |
| 46 | + } |
| 47 | +}; |
0 commit comments