Leetcode 298 Solution

This article provides solution to leetcode question 298 (binary-tree-longest-consecutive-sequence)

https://leetcode.com/problems/binary-tree-longest-consecutive-sequence

Solution

/**
 * 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 {
    int max_len;
public:
    int findLongestConsecutive(TreeNode* root)
    {
        if (root == NULL)
            return 0;

        int node_max_len = 1;
        if (root->left)
        {
            int left_max_len = findLongestConsecutive(root->left);
            if (root->val + 1 == root->left->val)
                node_max_len = max(left_max_len + 1, node_max_len);
        }

        if (root->right)
        {
            int right_max_len = findLongestConsecutive(root->right);
            if (root->val + 1 == root->right->val)
                node_max_len = max(right_max_len + 1, node_max_len);
        }

        max_len = max(max_len, node_max_len);
        return node_max_len;
    }

    int longestConsecutive(TreeNode* root) {
        max_len = 0;
        findLongestConsecutive(root);
        return max_len;
    }
};