leetcode 173. Binary Search Tree Iterator

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.

Calling next() will return the next smallest number in the BST.

Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.



class BSTIterator {
	vector<int>re;
	int k;
public:
	BSTIterator(TreeNode *root) {
		if (root == NULL)
			return ;
		vector<TreeNode*>que;
		que.push_back(root);
		bool f = true;
		while (!que.empty())
		{
			if (f&&que.back()->left != NULL)
				que.push_back(que.back()->left);
			else
			{
				re.push_back(que.back()->val);
				TreeNode*n = que.back(); que.pop_back();
				if (n->right != NULL)
				{
					que.push_back(n->right);
					f = true;
				}
				else
					f = false;
			}
		}
		k = 0;
	}

	/** @return whether we have a next smallest number */
	bool hasNext() {
		return re.size() > k;
	}

	/** @return the next smallest number */
	int next() {
		return re[k++];
	}
};

accepted


你可能感兴趣的:(LeetCode)