173. Binary Search Tree Iterator
仅供自己学习
思路:
我们可以通过中序遍历先把每个节点存放于一个数组里,然后对于next函数,因为题目说了next一定是有效的,所以我们我们只需要返回索引在的位置的元素,并把索引加一对于hasnext函数,只需判断是否大于数组的长度即可。
代码:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class BSTIterator { 13 private: 14 vector<int> arr; 15 int idx; 16 void inorder(TreeNode* root,vector<int>& res){ 17 if(root==NULL) return; 18 inorder(root->left,res); 19 res.push_back(root->val); 20 inorder(root->right,res); 21 } 22 vector<int> inorderTraversal(TreeNode* root){ 23 vector<int> res; 24 inorder(root,res); 25 return res; 26 } 27 28 public: 29 BSTIterator(TreeNode* root): idx(0), arr(inorderTraversal(root)) {} 30 31 int next() { 32 return arr[idx++]; 33 } 34 35 bool hasNext() { 36 return (idx < arr.size()); 37 } 38 }; 39 40 41 /** 42 * Your BSTIterator object will be instantiated and called as such: 43 * BSTIterator* obj = new BSTIterator(root); 44 * int param_1 = obj->next(); 45 * bool param_2 = obj->hasNext(); 46 */
另一种方法就是单调栈。在next函数我们一直深入这个节点的左节点,并把它们加入进栈中,当遇到NULL节点就结束深入,并且取出栈顶元素,pop掉,然后用一个变量存储取出的节点的val值,再移动到这个节点的右节点重复这个过程,这样就能把所有的节点都能遍历到,并且不需要一次装入所有的元素,最后我们再返回存储val值得变量即可。 对于hasnext函数,只要栈不为空或者当前节点不为NULL就返回true,否则返回false
代码:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class BSTIterator { 13 private: 14 stack<TreeNode*> st; 15 TreeNode* cur; 16 public: 17 BSTIterator(TreeNode* root): cur(root) {} 18 19 int next() { 20 while(cur){ 21 st.push(cur); 22 cur=cur->left; 23 } 24 cur=st.top(); st.pop(); 25 int temp =cur->val; 26 cur=cur->right; 27 return temp; 28 } 29 30 bool hasNext() { 31 if(cur != nullptr||!st.empty()) return true; 32 return false; 33 } 34 }; 35 36 37 /** 38 * Your BSTIterator object will be instantiated and called as such: 39 * BSTIterator* obj = new BSTIterator(root); 40 * int param_1 = obj->next(); 41 * bool param_2 = obj->hasNext(); 42 */