C++ 中的二叉搜索树迭代器


假设我们要制作一个二叉树迭代器。它将具有两种方法。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,则从节点的右侧推送中序后继
  • 返回当前的值
  • 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()

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

Next: 3
Next: 7
1
Next: 9
1
Next: 15
1
Next: 20
0

更新时间: 2020 年 5 月 4 日

2K+ 浏览

提升你的职业

通过完成课程来获得认证

开始学习
广告