[leetcode 298] Binary Tree Longest Consecutive Sequence---求二叉树连续序列的长度

Question:

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.


分析:

可以从递归角度考虑问题,

如果根节点为NULL,直接返回结果为0;

如果根节点不为空,但没有左右节点,说明连续数列只有1个;

如果有左孩子或是右孩子,判断当前节点的值是不是与父节点的值是不是连续的,如果是则将当前len值+1,如果不是,说明可以与父节点断开,len的长度重新赋值为1;

len表示从根节点开始到当前节点为止最大的连续数列长度,以此len值为基础,分别求解当前节点的左右子树连续数列的最大长度。

最后可以知道,到当前节点为止的最大连续数列长度为len、以len为基础的左右子树连续序列长度三者的最大值。


代码如下:

<span style="font-size:14px;">/**
 * 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:
    int longestConsecutive(TreeNode* root) {
        return longest(root, NULL, 0);
    }
private:
    int longest(TreeNode* now, TreeNode* parent, int len) {
        if (!now) return len;
        len = (parent && now->val == parent->val + 1) ? len + 1 : 1;
        return max(len, max(longest(now->left, now, len), longest(now->right, now, len)));
    }
};</span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值