C++ Inorder traversal plus recursion solution


  • 0
    W

    Time complexity: O(n)
    Space complexity: O(n)

    class Solution {
    public:
    
        // inorder traversal
        void isValidBST_recursion(TreeNode* root, vector<int> & res){
            if(root == nullptr) return;
            isValidBST_recursion(root->left, res);
            res.push_back(root->val);
            isValidBST_recursion(root->right, res);
            return;
        }
        
        bool isValidBST(TreeNode* root) {
            if(root == nullptr || (root->left == nullptr && root->right == nullptr)) return true;
            vector<int> res;
            isValidBST_recursion(root, res);
            int size = res.size();
            for(int i = 0; i<size-1; i++){
                if(res[i] >= res[i+1]) return false;
            }
            return true;
        }
    };
    

    Are there any ways to optimize my code?


Log in to reply
 

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