Leetcode#173 Binary Search Tree Iterator

原题地址

普遍的做法是:用栈保存从根节点到当前尚未遍历过的最小节点的路径(栈顶始终是最小节点)

constructor:遍历至最小节点,同时将路径上出现的节点压栈保存

hasNext:返回栈里面是否还有元素

next:栈顶元素即为所求,弹栈的同时更新栈,使栈里始终保存的是从根节点到剩余未遍历节点的最小节点的路径

因为每个元素入栈+出栈各一次,所以平均时间复杂度是O(1)。

代码:

 1 class BSTIterator {
 2 public:
 3     stack<TreeNode *> st;
 4     
 5     BSTIterator(TreeNode *root) {
 6         pushLeft(root);
 7     }
 8 
 9     /** @return whether we have a next smallest number */
10     bool hasNext() {
11         return !st.empty();
12     }
13 
14     /** @return the next smallest number */
15     int next() {
16         if (!hasNext())
17             return -1;
18             
19         TreeNode *top = st.top();
20         st.pop();
21 
22         if (top->right)
23             pushLeft(top->right);
24         
25         return top->val;
26     }
27     
28     void pushLeft(TreeNode *root) {
29         while (root) {
30             st.push(root);
31             root = root->left;
32         }
33     }
34 };
原文地址:https://www.cnblogs.com/boring09/p/4251790.html