Share my cpp solution


  • 0
    O
    /**
     * 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 {
        void helper(TreeNode* root, int cur_val, int &max_val) {
            max_val = max(max_val, cur_val);
            if (root->left != NULL) {
                if (root->left->val == root->val + 1) {
                    helper(root->left, cur_val + 1, max_val);
                } else {
                    helper(root->left, 1, max_val);
                }
            }
            if (root->right != NULL) {
                if (root->right->val == root->val + 1) {
                    helper(root->right, cur_val + 1, max_val);
                } else {
                    helper(root->right, 1, max_val);
                }
            }
        }
    public:
        int longestConsecutive(TreeNode* root) {
            if (root == NULL) {
                return 0;
            }
            int max_val = 1;
            helper(root, 1, max_val);
            return max_val;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.