问题描述
给定一个二叉树,你需要找出二叉树中最长的连续序列路径的长度。
请注意,该路径可以是递增的或者递减的。另一方面,路径可以是子-父-子顺序,并不一定是父-子顺序。
解题报告
- 从根节点开始,依次对左右孩子节点进行遍历。
- 返回从每个节点开始的最长的增长序列
inc
以及最长的下降序列dec
。 - 如果左孩子的值比当前值小,则当前节点与左孩子形成下降序列,所以
dec
更新为left_child(dec)+1
;如果左孩子的值比当前值大,则当前节点与左孩子形成上升序列,所以inc
更新为left_child(inc)+1
- 对于右孩子做同样的操作。
时间复杂度: O ( n ) O(n) O(n)。整棵树会被遍历一遍。
空间复杂度: O ( n ) O(n) O(n)。最坏的情况下树的深度为 n n n。
实现代码
/**
* 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 {
private:
int maxval=0;
public:
int longestConsecutive(TreeNode* root) {
longstPath(root);
return maxval;
}
pair<int,int>longstPath(TreeNode* root){
if(root==NULL){
return {0,0};
}
int inc=1,dec=1;
if(root->left!=NULL){
pair<int, int> l=longstPath(root->left);
if(root->val==root->left->val+1)
dec=l.second+1;
else if(root->val==root->left->val-1)
inc=l.first+1;
}
if(root->right!=NULL){
pair<int, int> r=longstPath(root->right);
if(root->val==root->right->val+1)
dec=max(dec,r.second+1);
else if(root->val==root->right->val-1)
inc=max(inc,r.first+1);
}
maxval=max(maxval,inc+dec-1);
return {inc,dec};
}
};