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

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;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
LeetCode(力扣)上,有一个经典的算法题目叫做“最长连续序列”(Longest Continuous Increasing Subsequence),通常用C++或其他编程语言进行解答。这个题目的目的是找到一个给定整数数组最长递增子序列。递增子序列是数组的一段连续元素,它们按顺序严格增大。 这里是一个简单的C++解决方案思路: ```cpp #include <vector> using namespace std; class Solution { public: int longestContinuousIncreasingSubsequence(vector<int>& nums) { if (nums.empty()) return 0; // 避免空数组的情况 int n = nums.size(); vector<int> dp(n, 1); // dp[i] 表示以nums[i]结尾的最长递增子序列长度 int max_len = 1; // 初始化最长递增子序列长度为1 for (int i = 1; i < n; ++i) { // 遍历数组,从第二个元素开始 if (nums[i] > nums[i-1]) { // 如果当前元素比前一个大 dp[i] = dp[i-1] + 1; // 更新dp值,考虑加入当前元素后的增长长度 max_len = max(max_len, dp[i]); // 检查是否更新了最长序列长度 } } return max_len; // 返回最长连续递增子序列的长度 } }; ``` 在这个代码,我们使用了一个动态规划(Dynamic Programming)的方法,维护了一个数组`dp`来存储每个位置以该位置元素结尾的最大递增子序列长度。遍历过程,如果遇到当前元素大于前一个元素,则说明可以形成一个新的递增子序列,所以将`dp[i]`设置为`dp[i-1]+1`,并更新全局的最长序列长度。 如果你想要深入了解这个问题,可以问: 1. 这个问题的时间复杂度是多少? 2. 动态规划是如何帮助解决这个问题的? 3. 如何优化这个算法,使其空间复杂度更低?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值