|
| 1 | +/** |
| 2 | + * 549. Binary Tree Longest Consecutive Sequence II |
| 3 | + * https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given the root of a binary tree, return the length of the longest consecutive path in the tree. |
| 7 | + * |
| 8 | + * A consecutive path is a path where the values of the consecutive nodes in the path differ by one. |
| 9 | + * This path can be either increasing or decreasing. |
| 10 | + * - For example, [1,2,3,4] and [4,3,2,1] are both considered valid, but the path [1,2,4,3] is |
| 11 | + * not valid. |
| 12 | + * |
| 13 | + * On the other hand, the path can be in the child-Parent-child order, where not necessarily be |
| 14 | + * parent-child order. |
| 15 | + */ |
| 16 | + |
| 17 | +/** |
| 18 | + * Definition for a binary tree node. |
| 19 | + * function TreeNode(val, left, right) { |
| 20 | + * this.val = (val===undefined ? 0 : val) |
| 21 | + * this.left = (left===undefined ? null : left) |
| 22 | + * this.right = (right===undefined ? null : right) |
| 23 | + * } |
| 24 | + */ |
| 25 | +/** |
| 26 | + * @param {TreeNode} root |
| 27 | + * @return {number} |
| 28 | + */ |
| 29 | +var longestConsecutive = function(root) { |
| 30 | + let maxLength = 0; |
| 31 | + traverse(root); |
| 32 | + return maxLength; |
| 33 | + |
| 34 | + function traverse(node) { |
| 35 | + if (!node) return [0, 0]; |
| 36 | + |
| 37 | + let inc = 1; |
| 38 | + let dec = 1; |
| 39 | + |
| 40 | + if (node.left) { |
| 41 | + const [leftInc, leftDec] = traverse(node.left); |
| 42 | + if (node.val === node.left.val + 1) { |
| 43 | + dec = Math.max(dec, leftDec + 1); |
| 44 | + } else if (node.val === node.left.val - 1) { |
| 45 | + inc = Math.max(inc, leftInc + 1); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + if (node.right) { |
| 50 | + const [rightInc, rightDec] = traverse(node.right); |
| 51 | + if (node.val === node.right.val + 1) { |
| 52 | + dec = Math.max(dec, rightDec + 1); |
| 53 | + } else if (node.val === node.right.val - 1) { |
| 54 | + inc = Math.max(inc, rightInc + 1); |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + maxLength = Math.max(maxLength, inc + dec - 1); |
| 59 | + return [inc, dec]; |
| 60 | + } |
| 61 | +}; |
0 commit comments