Leetcode 173. Binary Search Tree Iterator | | Leetcode 173. Binary Search Tree Iterator 文章作者:Tyan博客:noahsnail.com | CSDN | 简书 1. Description 2. Solution1234567891011121314151617181920212223242526272829303132333435363738394041424344/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class BSTIterator {private: stack<TreeNode*> index;public: BSTIterator(TreeNode *root) { traverseLeft(root); } /** @return whether we have a next smallest number */ bool hasNext() { return !index.empty(); } /** @return the next smallest number */ int next() { TreeNode* current = index.top(); index.pop(); traverseLeft(current->right); return current->val; } void traverseLeft(TreeNode* root) { TreeNode* current = root; while(current) { index.push(current); current = current->left; } }};/** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */ Reference https://leetcode.com/problems/binary-search-tree-iterator/description/ 如果有收获,可以请我喝杯咖啡! 赏 微信打赏 支付宝打赏