Wednesday, 23 December 2015

LeetCode Validate Binary Search Tree

LeetCode Validate Binary Search Tree

/**

 * 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 fun(TreeNode* root,int mn,int mx,int * cmn,int * cmx){

        if(root==NULL)

         return true;

        if(root->val <= mn){

         if(mn==-2147483648 && *cmn==0)

             {

             *cmn=1;

             return (fun(root->left,mn,root->val,cmn,cmx) && fun(root->right,root->val,mx,cmn,cmx));

             }

           return false;

        }

        if(root->val >= mx)

         {

             if(mx==2147483647 && *cmx==0)

             {

             *cmx=1;

             return (fun(root->left,mn,root->val,cmn,cmx) && fun(root->right,root->val,mx,cmn,cmx));

             }

            return false;

         }

        return (fun(root->left,mn,root->val,cmn,cmx) && fun(root->right,root->val,mx,cmn,cmx));

    }

    bool isValidBST(TreeNode* root) {

        int cmn=0;

        int cmx=0;

        return fun(root,INT_MIN,INT_MAX,&cmn,&cmx);

    }

};

No comments:

Post a Comment