1、题目描述
实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。
调用 next() 将返回二叉搜索树中的下一个最小的数。
示例:
BSTIterator iterator = new BSTIterator(root);
iterator.next(); // 返回 3
iterator.next(); // 返回 7
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 9
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 15
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 20
iterator.hasNext(); // 返回 false
提示:
next() 和 hasNext() 操作的时间复杂度是 O(1),并使用 O(h) 内存,其中 h 是树的高度。
你可以假设 next() 调用总是有效的,也就是说,当调用 next() 时,BST 中至少存在一个下一个最小的数。
2、我的代码
/**
-
Definition for a binary tree node.
-
struct TreeNode {
-
int val;
-
TreeNode *left;
-
TreeNode *right;
-
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
-
};
/
class BSTIterator {
public:
BSTIterator(TreeNode root) {
mPRoot = root;
}/** @return the next smallest number /
int next() {
int val = 0;
TreeNode left_tmp = NULL;
TreeNode* cur_tmp = NULL;
TreeNode* father_tmp = NULL;if(mPRoot->left == NULL){ val = mPRoot->val; mPRoot = mPRoot->right; } else { father_tmp = mPRoot; left_tmp = mPRoot->left; cur_tmp = left_tmp; do { cur_tmp = left_tmp->left; if(cur_tmp != NULL){ father_tmp = left_tmp; left_tmp = cur_tmp; } }while(cur_tmp != NULL); val = left_tmp->val; father_tmp->left = left_tmp->right; } return val;
}
/** @return whether we have a next smallest number */
bool hasNext() {
if(mPRoot == NULL)
return false;
else
return true;
}TreeNode* mPRoot;
};
/**
- Your BSTIterator object will be instantiated and called as such:
- BSTIterator* obj = new BSTIterator(root);
- int param_1 = obj->next();
- bool param_2 = obj->hasNext();
*/
3、网上的好解法
a、把数据整理到有续的一维数组、队列里
b、利用stack,进行随机暂停处理,而不用先把所有数据处理一遍
4、自己可以改进的地方
运行效率和内存占用还不理想
5、优化代码至简无可简
/**
-
Definition for a binary tree node.
-
struct TreeNode {
-
int val;
-
TreeNode *left;
-
TreeNode *right;
-
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
-
};
/
class BSTIterator {
public:
stack<TreeNode> tree_stack;void INOrderleft(TreeNode* root) {
while(root != NULL){
tree_stack.push(root);
root = root->left;
};
}
BSTIterator(TreeNode* root) {
INOrderleft(root);
}/** @return the next smallest number /
int next() {
TreeNode cur_tmp = tree_stack.top();
tree_stack.pop();
if(cur_tmp->right != NULL) {
INOrderleft(cur_tmp->right);
}
return cur_tmp->val;
}/** @return whether we have a next smallest number */
bool hasNext() {
int size = tree_stack.size();
if(size > 0)
return true;
else
return false;
}
};
/**
- Your BSTIterator object will be instantiated and called as such:
- BSTIterator* obj = new BSTIterator(root);
- int param_1 = obj->next();
- bool param_2 = obj->hasNext();
*/
6、获得的思考
STL提供的工具类要多用