9ms c++ in-order traversal, beats 100% cpp submission


  • 0
    W
    class Solution {
    public:
        bool isValidBST(TreeNode* root) {
            if(!root) return true;
            vector<int> arr;
            travel(root, arr);
            for(int i = 1; i < arr.size(); i++){
                if(arr[i] <= arr[i - 1]) return false;
            }
            return true;
        }
        
        void travel(TreeNode* root, vector<int>& arr){
                if(root->left) travel(root->left, arr);
                arr.push_back(root->val);
                if(root->right) travel(root->right, arr);
        }
    };
    

    Checking the validation at last seems to be faster than keeping track of a prevNode or maxNode? Didn't expect that...


Log in to reply
 

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