[Leetcode] 549. Binary Tree Longest Consecutive Sequence II 解题报告

题目

Given a binary tree, you need to find the length of Longest Consecutive Path in Binary Tree.

Especially, this path can be either increasing or decreasing. For example, [1,2,3,4] and [4,3,2,1] are both considered valid, but the path [1,2,4,3] is not valid. On the other hand, the path can be in the child-Parent-child order, where not necessarily be parent-child order.

Example 1:

Input:
        1
       / \
      2   3
Output: 2
Explanation: The longest consecutive path is [1, 2] or [2, 1].

Example 2:

Input:
        2
       / \
      1   3
Output: 3
Explanation: The longest consecutive path is [1, 2, 3] or [3, 2, 1].

Note: All the values of tree nodes are in the range of [-1e7, 1e7].

思路

对于以root为根的树来说,符合条件的path可以分为两类:一类是不经过root的,一类是经过root的。不经过root的可以直接通过对其左子树和右子树的递归调用获得。经过root的有两种:一种是在其左子树上由下到上连续递增到root之后,在其右子树上由上到下连续递增;一种是在其左子树上由下到上连续递减到root之后,在其右子树上由上到下继续连续递减。我们取所有可能类型的path的最长长度即可。

代码

/**
 * 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) {
        if(root == NULL) {
            return 0;
        }
        // calculate the paths that go through the root
        int l1 = findPath(root->left, root->val, -1) + findPath(root->right, root->val, 1) + 1;
        int l2 = findPath(root->left, root->val, 1) + findPath(root->right, root->val, -1) + 1;
        int cur = max(l1, l2);
        // calcualte the paths that do not go through the root
        int childMax = max(longestConsecutive(root->left), longestConsecutive(root->right));
        return max(cur, childMax);
    }
private:
    int findPath(TreeNode* root, int prevVal, int diff){
        if(root == NULL) {
            return 0;
        }
        if(root->val == (prevVal + diff)) {
            int left = findPath(root->left, root->val, diff);
            int right = findPath(root->right, root->val, diff);
            return max(left, right) + 1;
        }
        else {
            return 0;
        }
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值