Share my C++ Solution


  • 0
    H
    /**
     * 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:
        bool BST(TreeNode* root, int& left, int& right, int &k, int& n){
            if(!root)return true;
            int k1=0,k2=0,left1,right1,left2,right2;
            bool f1=true,f2=true;
            if(root->left)f1=BST(root->left,left1,right1,k1,n)&&root->val>right1;
            if(root->right)f2=BST(root->right,left2,right2,k2,n)&&root->val<left2;
            if(f1&&f2){
                k=k1+k2+1;
                left=root->left?left1:root->val;
                right=root->right?right2:root->val;
                n=max(k,n);
                return true;
            }else return false;
        }
        int largestBSTSubtree(TreeNode* root) {
            if(!root) return 0;
            int n=0,k=0,left,right;
            bool f=BST(root,left,right,k,n);
            return n;
        }
    };

Log in to reply
 

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