173. Binary Search Tree Iterator
Posted The Tech Road
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了173. Binary Search Tree Iterator相关的知识,希望对你有一定的参考价值。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class BSTIterator { public: stack<TreeNode *> s; TreeNode *p; BSTIterator(TreeNode *root) { p = root; } /** @return whether we have a next smallest number */ bool hasNext() { return p != NULL || !s.empty(); } /** @return the next smallest number */ int next() { if (hasNext()) { while (p) { s.push(p); p = p->left; } p = s.top(); s.pop(); int val = p->val; p = p->right; return val; } return -1; } }; /** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class BSTIterator { public: stack<TreeNode *> s; BSTIterator(TreeNode *root) { while (root) { s.push(root); root = root->left; } } /** @return whether we have a next smallest number */ bool hasNext() { return !s.empty(); } /** @return the next smallest number */ int next() { if (hasNext()) { TreeNode* p = s.top(); s.pop(); int val = p->val; p = p->right; while (p) { s.push(p); p = p->left; } return val; } return -1; } }; /** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */
以上是关于173. Binary Search Tree Iterator的主要内容,如果未能解决你的问题,请参考以下文章
173.Binary search tree iterator
173. Binary Search Tree Iterator
leetcode@ [173] Binary Search Tree Iterator (InOrder traversal)
[LC] 173. Binary Search Tree Iterator