LeetCode 298. Binary Tree Longest Consecutive Sequence

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)。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值