c++ recursive solution easy to understand


  • 0
    Q
    /**
     * 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;
            if(!root->left && !root->right)
                return 1;
            return max(helper(root->left, root->val,1), helper(root->right,root->val,1));  
        }
        
        int helper(TreeNode* root, int cur, int num){
            if(root == nullptr)
                return num;
            if(!root->left && !root->right)
                if(root->val == cur+1)
                    return num+1;
                else
                    return num;
            
            if(root->val == cur+1){
                return max(helper(root->left,cur+1,num+1), helper(root->right,cur+1,num+1));
            }
            else
                return max(helper(root->left,root->val,1), helper(root->right,root->val,1));
            
        }
    };
    

Log in to reply
 

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