298. Binary Tree Longest Consecutive Sequence

Problem:

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).

Example 1:

Input:

   1
    \
     3
    / \
   2   4
        \
         5

Output: 3

Explanation: Longest consecutive sequence path is 3-4-5, so return 3.

Example 2:

Input:

</strong> 2 \ 3 / 2
/ 1

Output: 2

Explanation: </strong>Longest consecutive sequence path is 2-3, not 3-2-1, so return 2.</pre>

Solutions:

/**
 * 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 == nullptr)    return 0;
        int consecutiveLen = 1;
        return helper(root, consecutiveLen);
    }
private:
    int helper(TreeNode* root, int& consecutiveLen) {
        int ret = 0;
        if (root->left) {
            int leftConsecutive = 1;
            ret = max(ret, helper(root->left, leftConsecutive));
            if (root->val + 1 == root->left->val) {
                consecutiveLen = max(consecutiveLen, 1 + leftConsecutive);
            }
        }

        if (root->right) {
            int rightConsecutive = 1;
            ret = max(ret, helper(root->right, rightConsecutive));
            if (root->val + 1 == root->right->val) {
                consecutiveLen = max(consecutiveLen, 1 + rightConsecutive);
            }
        }

        ret = max(ret, consecutiveLen);

        return ret;
    }

};

results matching ""

    No results matching ""