C++面試基礎知識複習系列——四
阿新 • • 發佈:2018-12-09
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_); } } }