Article Directory
Problem Description
Given a binary tree, you need to find the length of the longest continuous sequence path in the binary tree.
Please note that the path can be increasing or decreasing. On the other hand, the path can be in a child-father-child order, not necessarily in a parent-child order.
Problem solving report
- Starting from the root node, traverse the left and right child nodes in sequence.
- Returns the longest increasing sequence and the longest decreasing sequence starting from each node .
inc
dec
- If the value of the left child is smaller than the current value, the current node and the left child form a descending sequence, so
dec
update toleft_child(dec)+1
; if the value of the left child is greater than the current value, the current node and the left child form an ascending sequence, soinc
updateleft_child(inc)+1
- Do the same for the right child.
time complexity: . The whole tree will be traversed again.
Space complexity: . In the worst case, the depth of the tree is 。
Implementation code
/**
* 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};
}
};