c++ Short Beautiful Code


  • 2
    H
    int longestConsecutive(TreeNode* root) {
            if(root == NULL) return 0;
            int childMax = 0, cur = 0, l1 = 0, l2 = 0;
    
            l1 = findPath(root->left, root->val, -1) + findPath(root->right, root->val, 1) + 1;
            l2 = findPath(root->left, root->val, 1) + findPath(root->right, root->val, -1) + 1;
            cur = max(l1, l2);
            childMax = max(longestConsecutive(root->left), longestConsecutive(root->right));
            
            return max(cur, childMax);
        }
        
        int findPath(TreeNode* root, int prevVal, int diff){
            if(root == NULL) return 0;
            
            if(root->val == (prevVal + diff)) 
                return max(findPath(root->left, root->val, diff), findPath(root->right, root->val, diff)) + 1;
            else
                return 0;
        }

  • 0
    Q

    Beautiful solution! Very easy to understand!


  • 0
    H

    Thank You! : )


Log in to reply
 

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