Bottom up in c++


  • 0
    S

    As topic

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

Log in to reply
 

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