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

Have you met this question in a real interview?

Yes

Example

For example,

   1
    \
     3
    / \
   2   4
        \
         5

Longest consecutive sequence path is3-4-5, so return3.

   2
    \
     3
    / 
   2    
  / 
 1

Longest consecutive sequence path is2-3,not3-2-1, so return2.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    /**
     * @param root the root of binary tree
     * @return the length of the longest consecutive sequence path
     */
    int longestConsecutive(TreeNode* root) {
        // Write your code here
        int maxLen = 0;
        helper(root, 0, maxLen);
        return maxLen;
    }

    void helper(TreeNode* root, int curLen, int &maxLen) {
        if (!root)
            return;
        ++curLen;
        if (curLen > maxLen)
            maxLen = curLen;
        int tempLen = 0;
        if (root->left && root->left->val == root->val + 1)
            tempLen = curLen;
        helper(root->left, tempLen, maxLen);

        tempLen = 0;
        if (root->right && root->right->val == root->val + 1)
            tempLen = curLen;
        helper(root->right, tempLen, maxLen);
    }
};

results matching ""

    No results matching ""