Leetcode 173 Binary Search Tree iterator

题目描述

Leetcode 173 Binary Search Tree iterator

类似于通过栈实现二叉查找树的中序遍历,将其转换为链表,将每个树节点的left指针当做next的使用。代码如下:

class BSTIterator {
public:
	TreeNode* head;
	BSTIterator(TreeNode* root) {
		bool first = false;
		deque<TreeNode*> stack;
		head = new TreeNode(-1);
		if (root != NULL) {
			if (root->right != NULL) {
				stack.push_back(root->right);
				root->right = NULL;
			}
			stack.push_back(root);
			if (root->left != NULL) {
				stack.push_back(root->left);
				root->left = NULL;
			}
		}
		TreeNode* pre = head;
		while (!stack.empty()) {
			TreeNode* cur = stack.back();
			stack.pop_back();
			if (cur->right != NULL) {
				stack.push_back(cur->right);
				cur->right = NULL;
			}
			if (cur->left == NULL) {
				pre->left = cur;
				pre = cur;
			}else {
				stack.push_back(cur);
				stack.push_back(cur->left);
				cur->left = NULL;
			}
		}
		pre->left = NULL;
	}

	/** @return the next smallest number */
	int next() {
		head = head->left;
		return head->val;
	}

	/** @return whether we have a next smallest number */
	bool hasNext() {
		if (head->left != NULL)
			return true;
		else
			return false;
	}
};