[Leetcode] 298. Binary Tree Longest Consecutive Sequence 解题报告

本文探讨了如何在二叉树中寻找最长连续序列路径的问题,并通过深度优先搜索(DFS)的方法来解决这一挑战。文章提供了详细的算法思路及C++实现代码。

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

题目

Given a binary tree, find 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 need to be from parent to child (cannot be the reverse).

For example,

   1
    \
     3
    / \
   2   4
        \
         5
Longest consecutive sequence path is 3-4-5, so return 3.
   2
    \
     3
    / 
   2    
  / 
 1
Longest consecutive sequence path is 2-3,not3-2-1, so return 2.

思路

由于树上的全局最长长度可能和其root没有任何关系(有可能其最长长度对应的起点是root的孩子的孩子。。。),所以我们必须同时记录一个全局最大长度和一个局部最大长度。每次递归的时候更新局部最大长度,一旦发现局部最大长度超过了全局最大长度,则更新全局最大长度。具体实现可以采用DFS。

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int longestConsecutive(TreeNode* root) {
        if(root == NULL) {
            return 0;
        }
        int global_max = 0;
        dfs(root, global_max, root->val - 1, 0);
        return global_max;
    }
private:
    void dfs(TreeNode* root, int &global_max, int pre_value, int local_max) {
        if(root == NULL) {
            return;
        }
        int len = 1;
        if(root->val == pre_value + 1) {
            len = local_max + 1;
        }
        global_max = max(global_max, len);
        dfs(root->left, global_max, root->val, len);
        dfs(root->right, global_max, root->val, len);
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值