打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
​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:二叉树的序列化与反序列化

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
LeetCode算法题-Average of Levels in Binary Tree(Java实现)
1026. Maximum Difference Between Node and Ancestor (M)
【101-Symmetric Tree(对称树)】
求二叉树的结点个数
刻意练习:LeetCode实战 -- Task20. 对称二叉树
二叉搜索树操作集锦
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服