C++面试基础知识复习系列——四

1、查找;

查找算法 平均时间复杂度 空间复杂度 查找条件
顺序查找 O(n) O(1)
二分查找 O(log2n) O(1) 有序
哈希查找 O(1) O(n)
二叉查找树 O(log2n)    
红黑树 O(log2n)    
B/B+树 O(log2n)    

2、二叉树的遍历。

1>先序遍历;

2>中序遍历;

3>后续遍历;

4>层次遍历;

三种遍历的非递归代码:

#include <bits/stdc++.h>
using namespace std;
struct TreeNode{
  int val_;
  TreeNode* left_;
  TreeNode* right_;
};

//非递归先序遍历
void preOrder(TreeNode* pRoot){
  stack<TreeNode*> nodeStack;
  TreeNode* p=pRoot;

  while (p||!nodeStack.empty()) {
      while (p) {
          //visit p
          nodeStack.push(p);
          p=p->left_;
        }

      if(!nodeStack.empty()){
          p=nodeStack.top();
          nodeStack.pop();
          p=p->right_;
        }
    }
}

//非递归中序遍历
void inOrder(TreeNode* pRoot){
  stack<TreeNode*> nodeStack;
  TreeNode* p=pRoot;

  while (p||!nodeStack.empty()) {
      while (p) {
          nodeStack.push(p);
          p=p->left_;
        }

      if(!nodeStack.empty()){
          p=nodeStack.top();
          //visit p
          nodeStack.pop();
          p=p->right_;
        }
    }
}

//非递归后续遍历
void postOrder(TreeNode* pRoot){
  stack<TreeNode*> nodeStack;
  //当前访问的节点
  TreeNode* cur=nullptr;
  //当前节点之前访问的节点
  TreeNode* pre=nullptr;
  while(!nodeStack.empty()){
      cur=nodeStack.top();
      //当前节点为叶子节点/pre是cur的孩子节点
      if((!cur->left_&&!cur->right_)||(
           cur->left_==pre||cur->right_==pre)){
          //visit p;
          nodeStack.pop();
          pre=cur;
        }else{
          if(cur->left_)
            nodeStack.push(cur->left_);

          if(cur->right_)
            nodeStack.push(cur->right_);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_40825228/article/details/82631828