1 括号匹配题
bool test(string s){
if(s.size() %2 ==1)return false;
stack<char> s1;
int len = s.size();
for( int i=0;i<len;i++){
if(s[i] == '{' || s[i] == '[' || s[i]=='(')
s1.push(s[i]);
if(s[i]==' ')break;
if(s[i]==')'){
if(!s1.empty() && s1.top()=='(')s1.pop();
else return false;
}
else if(s[i]==']'){
if(!s1.empty() && s1.top() =='[')s1.pop();
else return false;
}
else if(s[i]=='}'){
if(!s1.empty() && s1.top() == '{')s1.pop();
else return false;
}
}
if(!s1.empty())return false;
else
return true;
}
2 二叉树的先序遍历非递归
struct BitNode {
int val;
struct BitNode *left;
struct BitNode *right;
}
void First_bianli(BitNode *head){
if (head == NULL) return ;
stack<BitNode*> s;
BitNode *p = head;
while (p!=NULL || !s.empty()){
if(p!=NULL){
cout<<p->val;
s.push(p);
p = p->left;
}
else{
BitNode *tem = s.top();
s.pop();
p = tem->right;
}
}
}
3 二叉树的中序遍历,非递归
void Mid_bianli(BitNode *head){
if(head == NULL) return ;
BitNode *p =head;
stack<BitNode*> s;
while(p != NULL || !s.empty()){
if(p){
s.push(p);
p = p->left;
}
else{
BitNode *tem = s.top();
cout<<tem->val;
s.pop();
p = tem->right;
}
}
}
4 二叉树的后序遍历非递归
5 二叉树的层次遍历非递归
//采用队列queue实现,
void Cengci_bianli(BitNode *head){
if(head == NULL) return ;
queue<BitNode *> q;
BitNode *p = head;
q.push(p);
while(!q.empty()){
BitNode *tem = q.front();
cout<<tem->val;
if(tem->left)q.push(tem-left);
if(tem->right)q.push(tem->right);
q.pop();
}
}
6 二维有序数组查找
//对数组的每一行采用二分法查找
bool find2(vector<vector<int>> a ,int target){
int len = a.size();
for(int i = 0; i<len;i++){
int low = 0 ;
int high = len -1 ;
while(low <= high){
int mid = (low +high)/2;
if(a[i][mid] == target)return true;
else if(a[i][mid] > target)high = mid -1;
else low = mid +1;
}
}
return false;
}
//从矩阵的左下角开始向右遍历,如果数组元素大于目标值,则向上查找,若该列没有,则继续向右遍历;如果数组元素小于目标值,则向右遍历。
bool find3(vector<vector<int>> a ,int target ){
// 从数组的最左下角开始找,比数组元素大,向右边找,比数组元素小,往上找
int len = a.size();
for(int i = 0;i<a.size();i++) {
if (a[len - 1][i] < target)continue;
else if (a[len - 1][i] == target)return true;
else {
for (int j = len - 1; j >= 0; j--) {
if (a[j][i] == target)return true;
else if (a[j][i] > target)continue;
else break;
}
}
}
return false;
}
//从左下角向右开始遍历,对每一列采用二分查找的方式去查找。
bool find4(vector<vector<int>> a ,int target){
int len = a.size();
for(int i =0;i<len;i++){
if(a[len-1][i] == target)return true;
else if(a[len-1][i] < target)continue;
else{
int low = 0;
int high = len-1;
while (low <= high){
int mid = (low+high)/2;
if(a[mid][i] == target)return true;
else if(a[mid][i] > target)high = mid -1;
else low = mid+1;
}
}
}
return false;
}