C++ Solution using DFS with O(n) time complexity


  • 0
    Y
    /**
     * 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) {
            int ans = 0, cnt = 0;
            if(!root)
                return ans;
            dfs(root, ans);
            return ans;
        }
        
        int dfs(TreeNode* root, int &ans){
            int lcnt = 0, rcnt = 0;
            if(root->left){
                lcnt = dfs(root->left, ans);
                if(root->val - root->left->val == -1){
                    ++ lcnt;
                    ans = max(ans, lcnt);
                }else
                    lcnt = 0;
            }
            if(root->right){
                rcnt = dfs(root->right, ans);
                if(root->val - root->right->val == -1){
                    ++ rcnt;
                    ans = max(ans, rcnt);
                }else
                    rcnt = 0;
            }
            if(!lcnt && !rcnt){
                ans = max(ans, 1);
                return 1;
            }else
                return max(lcnt, rcnt);
        }
    };

Log in to reply
 

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