​LeetCode刷题实战298:二叉树最长连续序列

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 二叉树最长连续序列,我们先来看题面:

https://leetcode-cn.com/problems/binary-tree-longest-consecutive-sequence/

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).

给你一棵指定的二叉树,请你计算它最长连续序列路径的长度。

该路径,可以是从某个初始结点到树中任意结点,通过「父 - 子」关系连接而产生的任意路径。

这个最长连续的路径,必须从父结点到子结点,反过来是不可以的。

示例

解题

找出左右结点中可能的更长的路径,进行保存

/**
 * 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:
    void helper(TreeNode* root,int count,int& max_count){
        if(root==NULL){//终止条件
            return;
        }
        //若左结点不为空,则可以接着遍历
        if(root->left){
          //若左结点和根节点的值的关系满足连续,则调整长度
            if(root->val+1==root->left->val){
                max_count=max(max_count,count+1);
                helper(root->left,count+1,max_count);
            }
            else{
              //否则将长度重新置为1调整
                helper(root->left,1,max_count);
            }
        }
        //若右结点和根节点的值的关系满足连续,则调整长度
        if(root->right){
            if(root->val+1==root->right->val){
                max_count=max(max_count,count+1);
                helper(root->right,count+1,max_count);
            }
            else{
              //否则将长度重新置为1进行统计
                helper(root->right,1,max_count);
            }
        }
    }
    int longestConsecutive(TreeNode* root) {
        if(root==NULL){
            return 0;
        }
        int max_count=1;//初始长度
        helper(root,1,max_count);
        return max_count;
    }
};

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-280题汇总,希望对你有点帮助!

LeetCode刷题实战281:锯齿迭代器

LeetCode刷题实战282:给表达式添加运算符

LeetCode刷题实战283:移动零

LeetCode刷题实战284:顶端迭代器

LeetCode刷题实战285:二叉搜索树中的顺序后继

LeetCode刷题实战286:墙和门

LeetCode刷题实战287:寻找重复数

LeetCode刷题实战288:单词的唯一缩写

LeetCode刷题实战289:生命游戏

LeetCode刷题实战290:单词规律

LeetCode刷题实战291:单词规律II

LeetCode刷题实战292:Nim 游戏

LeetCode刷题实战293:翻转游戏

LeetCode刷题实战294:翻转游戏II

LeetCode刷题实战295:数据流的中位数

LeetCode刷题实战296:最佳的碰头地点

LeetCode刷题实战297:二叉树的序列化与反序列化

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序IT圈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值