40ms c++ solution


  • 0
    X
    /**
     * 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(NULL == root) return 0;
            int currentDepth=1;
            int maxDepth=-1;
            calculateSequence(root, currentDepth, maxDepth);
            return maxDepth;
        }
        
        void calculateSequence(TreeNode * root, int currentDepth, int & maxDepth) {
            if(NULL == root->left && NULL == root->right) {
                maxDepth = max(currentDepth, maxDepth); return;
            }
            if(NULL != root->left) {
                if(root->val + 1 == root->left->val) {
                    calculateSequence(root->left, currentDepth+1, maxDepth);
                } else {
                    maxDepth = max(currentDepth, maxDepth);
                    calculateSequence(root->left, 1, maxDepth);
                }
            }
            if(NULL != root->right) {
                if(root->val + 1 == root->right->val) {
                    calculateSequence(root->right, currentDepth+1, maxDepth);
                } else {
                    maxDepth = max(currentDepth, maxDepth);
                    calculateSequence(root->right, 1, maxDepth);
                }
            }
        }
    };

Log in to reply
 

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