标签:
使用栈来记录可能的路径,栈顶一直是下一个元素。
class BSTIterator { public: stack<TreeNode *> path; BSTIterator(TreeNode *root) { path = stack<TreeNode *>(); TreeNode *node = root; while (node != NULL) { path.push(node); node = node->left; } } /** @return whether we have a next smallest number */ bool hasNext() { return !path.empty(); } /** @return the next smallest number */ int next() { TreeNode *node = path.top(); path.pop(); int ret = node->val; if (node->right != NULL) { node = node->right; path.push(node); while (node->left != NULL) { node = node->left; path.push(node); } } return ret; } };
[leetcode]Binary Search Tree Iterator
标签:
原文地址:http://www.cnblogs.com/lautsie/p/4196759.html