코테준비 - Binary Search Tree Iterator

정상화·2023년 2월 26일

LeetCode

목록 보기
160/222

Binary Search Tree Iterator

class BSTIterator {
private:
    vector<int> vec;
    int i = 0;

    void inOrder(TreeNode* root){
        if (!root->left && !root->right) {
            vec.push_back(root->val);
            return;
        }
        if (root->left) {
            inOrder(root->left);
        }
        vec.push_back(root->val);
        if (root->right) {
            inOrder(root->right);
        }
    }
public:
    BSTIterator(TreeNode* root) {
        inOrder(root);
    }

    int next() {
        return vec[i++];
    }

    bool hasNext() {
        return i < vec.size();
    }
};
profile
백엔드 희망

0개의 댓글