solution using inorder search


  • 0

    Just see it,and you'll know it.
    The point is that the "pre" must be global variable ,if you put it in the function,when recursion happens, it will become "NULL",and be out of action.

    /**
     * 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:
        TreeNode* pre=NULL;
        bool isValidBST(TreeNode* root) {
           if(root==NULL)
               return true;
            else 
            {
                if(!isValidBST(root->left)) return false;
                if(pre!=NULL&&root->val<=pre->val) return false;
                pre=root;
                if(!isValidBST(root->right)) return false;
                return true;
            }
        }
    };
    

Log in to reply
 

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