Binary Search Tree Iterator 二叉搜索树迭代器

实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。

调用 next() 将返回二叉搜索树中的下一个最小的数。

注意: next() 和hasNext() 操作的时间复杂度是O(1),并使用 O(h) 内存,其中 是树的高度。

思路:这道题在类中声明一个stack变量的s,在初始化时根据“右-根-左”遍历的顺序(保证访问到的数字由大到小)递归调用自身往s中填写数字,这样在初始化时s中保存的便是当前节点为根节点后序遍历的数字,栈顶元素便是最小的元素。

参考代码:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class BSTIterator {
public:
	BSTIterator(TreeNode *root) {
		if(root) createStack(root);
	}
	void createStack(TreeNode *root) {
		if (root->right) createStack(root->right);
		if (root) s.push(root->val);
		if (root->left) createStack(root->left);
	}
	/** @return whether we have a next smallest number */
	bool hasNext() {
		return !s.empty();
	}

	/** @return the next smallest number */
	int next() {
		int tmp = s.top();
		s.pop();
		return tmp;
	}
private:
	stack<int> s;
};

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = BSTIterator(root);
 * while (i.hasNext()) cout << i.next();
 */

猜你喜欢

转载自blog.csdn.net/qq_26410101/article/details/81608743