【leetcode】298 Binary Tree Longest Consecutive Sequence(二叉树最长连续序列)

这篇文章介绍了如何使用普通深度优先搜索(DFS)算法解决二叉树中寻找最长连续节点序列的问题。通过递归维护当前路径长度和全局最长长度,避免了回溯,展示了如何在遍历时快速找到最长连续序列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值