이진 트리에 대해 하나의 반복자를 만들고 싶다고 가정합니다. 두 가지 방법이 있을 것입니다. 다음 요소를 반환하는 next() 메서드와 부울 값을 반환하는 hasNext() 메서드는 다음 요소가 있는지 여부를 나타냅니다. 트리가 다음과 같다면 -

그리고 함수 호출의 순서는 [next(), next(), hasNext(), next(), hasNext(),next(), hasNext(),next(), hasNext()입니다. 출력은 [3,7,true,9,true,15,true,20,false]
가 됩니다.이 문제를 해결하기 위해 다음 단계를 따릅니다. −
- next와 hasNext의 두 가지 방법이 있습니다.
- next() 메소드는 다음과 같습니다 -
- curr :=스택 상단 요소 및 팝업 상단 요소
- curr의 오른쪽이 null이 아니면 노드의 오른쪽에서 inorder 계승자를 푸시합니다.
- 현재의 반환 값
- hasNext() 메소드는 다음과 같습니다 -
- 스택이 비어 있지 않으면 true를 반환하고, 그렇지 않으면 false를 반환합니다.
이해를 돕기 위해 다음 구현을 살펴보겠습니다. −
예시
#include <bits/stdc++.h>
using namespace std;
class TreeNode{
public:
int val;
TreeNode *left, *right;
TreeNode(int data){
val = data;
left = right = NULL;
}
};
void insert(TreeNode **root, int val){
queue<TreeNode*> q;
q.push(*root);
while(q.size()){
TreeNode *temp = q.front();
q.pop();
if(!temp->left){
if(val != NULL)
temp->left = new TreeNode(val);
else
temp->left = new TreeNode(0);
return;
} else {
q.push(temp->left);
}
if(!temp->right){
if(val != NULL)
temp->right = new TreeNode(val);
else
temp->right = new TreeNode(0);
return;
}else{
q.push(temp->right);
}
}
}
TreeNode *make_tree(vector<int> v){
TreeNode *root = new TreeNode(v[0]);
for(int i = 1; i<v.size(); i++){
insert(&root, v[i]);
}
return root;
}
class BSTIterator {
public:
stack <TreeNode*> st;
void fillStack(TreeNode* node){
while(node && node->val != 0){
st.push(node);
node=node->left;
}
}
BSTIterator(TreeNode* root) {
fillStack(root);
}
/** @return the next smallest number */
int next() {
TreeNode* curr = st.top();
st.pop();
if(curr->right && curr->right->val != 0){
fillStack(curr->right);
}
return curr->val;
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !st.empty();
}
};
main(){
vector<int> v = {7,3,15,NULL,NULL,9,20};
TreeNode *root = make_tree(v);
BSTIterator ob(root);
cout << "Next: " << ob.next() << endl;
cout << "Next: " << ob.next() << endl;
cout << ob.hasNext() << endl;
cout << "Next: " << ob.next() << endl;
cout << ob.hasNext() << endl;
cout << "Next: " << ob.next() << endl;
cout << ob.hasNext() << endl;
cout << "Next: " << ob.next() << endl;
cout << ob.hasNext() << endl;
} 입력
BSTIterator ob(root); ob.next() ob.next() ob.hasNext() ob.next() ob.hasNext() ob.next() ob.hasNext() ob.next() ob.hasNext()
출력
Next: 3 Next: 7 1 Next: 9 1 Next: 15 1 Next: 20 0