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).
For example,
1
\
3
/ \
2 4
\
5
Longest consecutive sequence path is 3-4-5, so return 3.
2
\
3
/
2
/
1
Longest consecutive sequence path is 2-3,not3-2-1, so return 2.
思路:
1. 和其他关于树的问题类似,并找出或统计某些特征。需要遍历树,一边遍历一边统计最长的连续序列。统计过程中,需要设置变量计算当前的长度,如果当前长度大于当前最大长度,这update。
2.
//代码1:
int longestConsecutive(TreeNode* root) {
return helper(root,0);
}
int helper(TreeNode* root,int&cur){
if(!root) {
cur=0;
return 0;
}
int lcur=cur,rcur=cur;
int left=helper(root->left,lcur);
if(!left||root->val==root->left->val+1){
left++;
lcur++;
}else
lcur=1;
int right=helper(root->right,rcur);
if(!right||root->val==root->right->val+1){
right++;
rcur++;
}else
rcur=1;
cur=max(lcur,rcur);
return max(left,right);
}
int longestConsecutive(TreeNode* root) {
return helper(root,NULL,0);
}
//参考解法三,思路刚好相反,一个冗长但易理解,一个简短但不易理解http://www.cnblogs.com/grandyang/p/5252599.html
//代码2:
int helper(TreeNode* root,TreeNode* parent,int cur){
if(!root) return cur;
cur=(parent&&root->val==parent->val+1)?cur+1:1;
return max(cur,max(helper(root->left,root,cur),helper(root->right,root,cur));
}
//代码1 vs 代码2
//代码1是从下往上加,所以先recursive到leaf之后再把结果传递到树根;代码2从上往下加,一开始就从root判断从root到当前层之间的最大长度(返回值)和当前长度(cur)。