2020-05-12
1.题目描述
二叉搜索树迭代器
2.题解
对于二叉搜索树而言,进行中序遍历就可以得到其有序序列,我们可以先对树进行遍历,将结果保存在
vector中,然后进行计算即可。
3.代码
173
/**
* 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) {
TreeNode* p=root;
while (p||!mystack.empty()){
while (p){
mystack.push(p);
p=p->left;
}
if (!mystack.empty()){
myvector.push_back(mystack.top()->val);
p=mystack.top();
mystack.pop();
p=p->right;
}
}
index=0;
}
/** @return the next smallest number */
int next() {
return myvector[index++];
}
/** @return whether we have a next smallest number */
bool hasNext() {
if (index>=myvector.size()) return false;
return true;
}
stack<TreeNode*> mystack;
vector<int> myvector;
int index;
};
/**
* 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();
*/
94
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> myvector;
stack<TreeNode*> mystack;
TreeNode* p=root;
while (p||!mystack.empty()){
while(p){
mystack.push(p);
p=p->left;
}
if (!mystack.empty()){
p=mystack.top();
mystack.pop();
myvector.push_back(p->val);
p=p->right;
}
}
return myvector;
}
};
145
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> myvector;
stack<TreeNode*> mystack;
TreeNode* p=root;
TreeNode* pre=p;
while (p||!mystack.empty()){
while (p){
mystack.push(p);
p=p->left;
}
TreeNode* top=mystack.top();
if (!top->right||pre==top->right){
myvector.push_back(top->val);
mystack.pop();
pre=top;
}else{
p=top->right;
}
}
return myvector;
}
};
98
一开始将pre设置成最小的int,没想到测试样例中竟然刚好出现了[-2147483648],只能使用long long
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode* root) {
// 对其进行中序遍历,看其是否是递增的即可
if (!root) return true; // 根节点为空
stack<TreeNode*> mystack;
TreeNode* p=root;
long long pre=(long long)INT_MIN-1; // 保留其中序遍历的上一个数,看是否满足递增的条件
while (p||!mystack.empty()){
while (p){
mystack.push(p);
p=p->left;
}
p=mystack.top();
mystack.pop();
if (p->val<=pre) return false;
pre=p->val;
p=p->right;
}
return true;
}
};