Lintcode 614 · Binary Tree Longest Consecutive Sequence II (二叉树后序遍历好题)

614 · Binary Tree Longest Consecutive Sequence II
Algorithms
Medium

Description
Given a binary tree, find the length(number of nodes) of the longest consecutive sequence(Monotonic and adjacent node values differ by 1) path.
The path could be start and end at any node in the tree

Example
Example 1:

Input:
{1,2,0,3}
Output:
4
Explanation:
1
/
2 0
/
3
0-1-2-3
Example 2:

Input:
{3,2,2}
Output:
2
Explanation:
3
/
2 2
2-3
Tags
Company
Google
Related Problems

472
Binary Tree Path Sum III
Hard

595
Binary Tree Longest Consecutive Sequence
Easy

619
Binary Tree Longest Consecutive Sequence III
Medium

717
Tree Longest Path With Same Value
Medium

解法1:后序遍历。helper()返回当前节点的incrLen 和 decrLen,同时维护当前最大的maxLen = max(maxLen, incrLen + decrLen - 1)。

/**
 * Definition of TreeNode:
 * 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) {
        if (!root) return 0;
        helper(root);
        return maxLen;
    }
private:
    int maxLen = 1;
    vector<int> helper(TreeNode *root) {
        if (!root) return {};
        int incrLen = 1, decrLen = 1;
        vector<int> left = helper(root->left); //<incrLen, decrLen>
        vector<int> right = helper(root->right); //<incrLen, decrLen>
        if (root->left && root->val == root->left->val + 1) {
            incrLen = left[0] + 1;
        } 
        if (root->left && root->val == root->left->val - 1) {
            decrLen = left[1] + 1;
        }

        if (root->right && root->val == root->right->val + 1) {
            incrLen = max(incrLen, right[0] + 1);
        }
        if (root->right && root->val == root->right->val - 1) {
            decrLen = max(decrLen, right[1] + 1);
        }
        maxLen = max(maxLen, incrLen + decrLen - 1);
        return {incrLen, decrLen};
    }
};
  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值