描述
给定一棵二叉树,找到最长连续序列路径的长度。
路径起点跟终点可以为二叉树的任意节点。
样例
1
/ \
2 0
/
3
返回 4 // 0-1-2-3
思路
对于每个节点root,求以root为起始节点的最长连续递增递增序列的长度up和最长连续递减序列的长度down,结果返回 < up,down >。初始化up, down均为1,left,right分别表示root左右子树的< up, down>,当root的左子树存在,若root左子树的值是root的值+1,up的值为左子树up+1;若root右子树的值是root的值-1,down的值为左子树down+1。当root的右子树存在时,也是同样的操作。
#ifndef C614_H
#define C614_H
#include<iostream>
#include<vector>
#include<algorithm>
#include<map>
using namespace std;
class TreeNode{
public:
int val;
TreeNode *left, *right;
TreeNode(int val){
this->val = val;
this->left = this->right = NULL;
}
};
class Solution {
public:
/**
* @param root: the root of binary tree
* @return: the length of the longest consecutive sequence path
*/
int longestConsecutive2(TreeNode * root) {
// write your code here
if (!root)
return 0;
helper(root);
return maxLength;
}
//返回节点的<最长升序,最长降序>
pair<int,int> helper(TreeNode *root)
{
if (!root)
return make_pair(0, 0);
//up表示最长升序的长度,down表示最长降序的长度
int up = 1, down = 1;
pair<int, int> left = helper(root->left);
pair<int, int> right = helper(root->right);
//右子树不为空,若root节点的值是左子树值+1,up值为最长递增序列长度加一
//若root节点的值是左子树值-1,down值为最长递减序列长度加一
if (root->left)
{
if (root->left->val == root->val + 1)
up = max(up, left.first + 1);
if (root->left->val == root->val - 1)
down = max(down, left.second + 1);
}
//左子树不为空,若root节点的值是右子树值+1,up值为最长递增序列长度加一
//若root节点的值是右子树值-1,down值为最长递增序列长度加一
if (root->right)
{
if (root->right->val == root->val + 1)
up = max(up, right.first + 1);
if (root->right->val == root->val - 1)
down = max(down, right.second + 1);
}
maxLength = max(maxLength, up + down - 1);
return make_pair(up, down);
}
int maxLength = 1;//最长连续序列路径的长度
};
#endif