[LeetCode 298] Binary Tree Longest Consecutive Sequence

本文介绍了一种在二叉树中寻找最长连续序列路径的方法。通过简单的递归算法,文章详细解释了如何从根节点开始,沿着父-子连接,找到最长的连续节点序列,并返回其长度。示例展示了输入树结构和预期输出,帮助理解算法的工作原理。

摘要生成于 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).

Have you met this question in a real interview?  Yes

Problem Correction

Example

Example 1:

Input:
   1
    \
     3
    / \
   2   4
        \
         5
Output:3
Explanation:
Longest consecutive sequence path is 3-4-5, so return 3.

Example 2:

Input:
   2
    \
     3
    / 
   2    
  / 
 1
Output:2
Explanation:
Longest consecutive sequence path is 2-3,not 3-2-1, so return 2.

分析

简单的递归就可以计算。

Code

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: the root of binary tree
     * @return: the length of the longest consecutive sequence path
     */
    int longestConsecutive(TreeNode * root) {
        // write your code here
        if (!root)
            return 0;
        
        int maxLen = 0;
        findLongest(root, 1, maxLen);
        return maxLen;
    }
    
    void findLongest(TreeNode* root, int len, int& maxLen)
    {
        if (!root)
            return;
        
        maxLen = max(maxLen, len);
        if (root->left)
        {
            if (root->val == root->left->val - 1)
                findLongest(root->left, len+1, maxLen);
            else
                findLongest(root->left, 1, maxLen);
        }
        
        if (root->right)
        {
            if (root->val == root->right->val - 1)
                findLongest(root->right, len+1, maxLen);
            else
                findLongest(root->right, 1, maxLen);
        }
    }
};

 

运行效率

 Your submission beats 76.60% Submissions!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值