题目来源
题目描述
给你一棵指定的二叉树,请你计算它最长连续序列路径的长度。
该路径,可以是从某个初始结点到树中任意结点,通过「父 - 子」关系连接而产生的任意路径。
这个最长连续的路径,必须从父结点到子结点,反过来是不可以的。
示例 1:
输入:
输出: 3
解析: 当中,最长连续序列是 3-4-5,所以返回结果为 3
示例 2:
输入:
输出: 2
解析: 当中,最长连续序列是 2-3。注意,不是 3-2-1,所以返回 2。
题目解析
注意,连续序列
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
int max = 0;
void process(TreeNode *root, int pre, int depth){
if(pre + 1 == root->val){
depth++;
}else{
depth = 1;
}
max = std::max(max, depth);
if(root->left != nullptr){
process(root->left, root->val, depth);
}
if(root->right != nullptr){
process(root->right, root->val, depth);
}
}
public:
int longestConsecutive(TreeNode *root) {
if(root == nullptr){
return 0;
}
process(root, root->val - 2, 1);
return max;
}
};
思路二:
class Solution {
int maxlen = 1;
public:
int longestConsecutive(TreeNode* root) {
if(!root) return 0;
dfs(root, 1);
return maxlen;
}
void dfs(TreeNode* root, int len)
{
if(!root) return;
maxlen = max(maxlen, len);
if(root->left)
{
if(root->val+1 == root->left->val)
dfs(root->left, len+1);//满足连续,长度+1
else
dfs(root->left, 1);//不满足,从新开始
}
if(root->right)
{
if(root->val+1 == root->right->val)
dfs(root->right, len+1);
else
dfs(root->right, 1);
}
}
};