描述
給定一棵二叉樹,找到最長連續序列路徑的長度。
路徑起點跟終點可以爲二叉樹的任意節點。
樣例
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