LeetCode刷题实战298:二叉树最长连续序列
共 4554字,需浏览 10分钟
·
2021-06-23 20:56
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;
}
};