LeetCode #173. 二叉搜索树迭代器 题解 C/C++

题目连接

struct TreeNode
{
     
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode():val(0),left(nullptr),right(nullptr){
     }
	TreeNode(int x):val(x),left(nullptr),right(nullptr){
     }
	TreeNode(int x,TreeNode *left,TreeNode *right):val(x),left(left),right(right){
     }
};


class BSTIterator {
     
private:
	void inorder(TreeNode *root,vector<int >& vec) {
     
		if(!root)return ;
		inorder(root->left,vec);
		vec.emplace_back(root->val);
		inorder(root->right,vec);
	} 
	vector<int> inorderTraversal(TreeNode *root) {
     
		vector<int> ret;
		inorder(root,ret);
		return ret; 
	}

	vector<int> buf;
	size_t idx;//索引
public:
	BSTIterator(TreeNode *root) {
     
		idx = 0;
		buf = inorderTraversal(root);
	}

	int next() {
     
		return buf[idx++];
	}

	bool hasNext() {
     
		return idx<buf.size();
	}
};

//迭代
class BSTIterator {
     
private:

	TreeNode *cur;
	stack<TreeNode *> stk;
public:
	BSTIterator(TreeNode *root) {
     
		cur = root;
	}

	int next() {
     
		while(cur) {
     
			stk.emplace(cur);
			cur = cur->left;
		}
		cur = stk.top();
		stk.pop();
		int ret = cur->val;
		cur = cur->right;
		return ret;
	}

	bool hasNext() {
     
		return cur || !stk.empty();
	}
};

你可能感兴趣的:(LeetCode,中序遍历,c++,二叉搜索树)