298.Binary Tree Longest Consecutive Sequence
Given the root of a binary tree, return the length of the longest consecutive sequence path.
The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path needs to be from parent to child (cannot be the reverse).

一开始以为要用回溯,其实用普通dfs即可,在递归时维护一个变量len记录此时的连续长度,当遇到不连续的情况时从1开始重新计算。同时维护一个变量max记录递归时遇到的最长的len,最后得到的max就是答案。

var longestConsecutive = function(root) {
    const helper = (root, len, target) => {
    	//termination condition
        if(root === null) return;
        if(root.val === target) len++;
        else len = 1;
        max = Math.max(len, max);
        helper(root.left, len, root.val + 1);
        helper(root.right, len, root.val + 1);
    }
    
    //boundary condition
    if(root === null) return 0;
    //record the max length of consecutive sequence
    let max = 0;
    helper(root, 0, root.val);
    return max;
};
Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐