Binary Tree Longest Consecutive Sequence
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) {
if(!root) {
return 0
}
let max = 0
const aux = (node, count) => {
if(!node) {
return
}
let leftCount = 0
let rightCount = 0
if(node.left) {
leftCount = node.left.val === node.val + 1 ? count + 1: 1
aux(node.left, leftCount)
}
if(node.right) {
rightCount = node.right.val === node.val + 1?
count + 1 : 1
aux(node.right, rightCount)
}
max = Math.max(leftCount, rightCount, count, max)
}
aux(root, 1)
return max
}