Binary Tree Longest Consecutive Sequence II
Description
null
Solution(javascript)
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var longestConsecutive = function(root) {
let max = 0
const aux = (node) => {
if(!node) {
return [null, 0, 0]
}
const [leftVal, leftInCount, leftDeCount] = aux(node.left)
const [rightVal, rightInCount, rightDeCount] = aux(node.right)
const val = node.val
let inCount = 1
let deCount = 1
if(node.val === leftVal + 1) {
inCount = leftInCount + 1
}
if(node.val === rightVal +1) {
inCount = Math.max(inCount, rightInCount+1)
}
if(node.val === leftVal - 1) {
deCount = leftDeCount + 1
}
if(node.val === rightVal - 1) {
deCount = Math.max(deCount, rightDeCount+1)
}
max = Math.max(
leftInCount, leftDeCount,
rightInCount, rightDeCount,
inCount,
deCount,
max
)
if(val === leftVal + 1 && val === rightVal - 1) {
max = Math.max(max, leftInCount + rightDeCount + 1)
}
if(val === leftVal - 1 && val === rightVal + 1) {
max = Math.max(max, leftDeCount + rightInCount + 1)
}
return [node.val, inCount, deCount]
}
aux(root)
return max
};