straightforward in-order traversal


  • 0
    S

    The only thing is to judge the array in strict increasing order using is_sorted. The default compare for is_sorted using <, that is when next element < prev_element it returns false. We only need change it to <= and problem is solved

    bool cmp(int a,int b) {return a<=b;}
    class Solution {
    public:
        bool isValidBST(TreeNode* root) {
            //in order will give a sorted array
            vector<int> v;
            inorder_traversal(root,v);
            return is_sorted(v.begin(),v.end(),cmp);//is_sorted will only return false when the next one < prev one!
            
        }
        void inorder_traversal(TreeNode* root,vector<int>& v)
        {
            if(!root) return;
            inorder_traversal(root->left,v);
            v.push_back(root->val);
            inorder_traversal(root->right,v);
        }
    };
    

Log in to reply
 

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