(1)链表某一段转置
for(int i=m;i<n;i++){
ListNode *temp=cur->next;
cur->next=temp->next;
temp->next=pre->next;
pre->next=temp;
}
while(cur != tail){
ListNode* temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
(2)二叉树遍历
结点:
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
前序:
vector<int> res;
void dfs(TreeNode* Node){
if(Node == nullptr) return;
res.push_back(Node->val);
dfs(Node->left);
dfs(Node->right);
}
中序:
vector<int> res;
void dfs(TreeNode* Node){
if(Node == nullptr) return;
dfs(Node->left);
res.push_back(Node->val);
dfs(Node->right);
}
后序:
vector<int> res;
void dfs(TreeNode* Node){
if(Node == nullptr) return;
dfs(Node->left);
dfs(Node->right);
res.push_back(Node->val);
}
层序遍历输出:
(1)修改遍历模板
void f(TreeNode* root,int level,vector<vector<int>> &res){
if(!root)return ;
if(level>=res.size()){//最新的深度,申请一个数组存储;
res.push_back(vector<int> {});
}
res[level].push_back(root->val);
f(root->left,level+1,res);;
f(root->right,level+1,res);;
}
vector<vector<int> > levelOrder(TreeNode* root) {
vector<vector<int>> res;;
f(root,0,res);;
return res;;
}
(2)广度优先(使用队列):逐层入列,逐层出列
vector<vector<int> > levelOrder(TreeNode* root) {
vector<vector<int> > vv;
if(!root){
return vv;//二叉树为空
}
queue<TreeNode*> qq;//队列存放相邻两层节点;
qq.push(root);
while(!qq.empty()){
vector<int> tempv;
int size=qq.size();
for(int i=0;i<size;++i){//将一层的节点size出队;
TreeNode* tt=qq.front();
qq.pop();
tempv.push_back(tt->val);
//将下一层的节点入队;
if(tt->left)qq.push(tt->left);
if(tt->right)qq.push(tt->right);
}
vv.push_back(tempv);;
}
return vv;
}
(3)并查集
class Un {
public:
Un(int n)
: fa(n) {
iota(fa.begin(), fa.end(), 0);
}
int find(int x) {
if (x != fa[x]) {
fa[x] = find(fa[x]);
}
return fa[x];
}
void merge(int x, int y) {
x = find(x), y = find(y);
fa[x] = y;
}
int operator[](int i) {
return find(i);
}
vector<int> fa;
};
(4)合并两个有序链表
public ListNode mergeTwoLists (ListNode l1, ListNode l2) {
if(l1 == NULL)
return l2;
if(l2 == NULL)
return l1;
ListNode* head = new ListNode(-1);
ListNode* tail = head;
while(l1 != NULL && l2 != NULL){
if(l1->val <= l2->val){
tail->next = l1;
l1 = l1->next;
}else{
tail->next = l2;
l2 = l2->next;
}
tail = tail->next;
}
tail->next = (l1 == null) ? l2:l1;
return head->next;
}
(5)合并k个有序链表(利用红黑树)
(将所有节点的val和节点地址封装成K-V结构保存进红黑树,val为K,节点为V,这样保存进红黑树里面就会有序了。然后中序遍历红黑树,将所有节点链接起来。)(考虑到有val重复的节点,所有用multimap去存储。)
ListNode *mergeKLists(vector<ListNode *> &lists)
{
multimap<int, ListNode*> mm;
for (int i = 0; i < lists.size(); i++)
{
ListNode* cur = lists[i];
while (cur)
{
mm.insert(make_pair(cur->val, cur));
cur = cur->next;
}
}
if (mm.size() == 0) // 树为空表明没有节点存入,直接返回空
{
return nullptr;
}
ListNode* head = mm.begin()->second;
ListNode* tail = nullptr;
for (auto& pair : mm)
{
if (tail)
{
tail->next = pair.second;
}
tail = pair.second;
}
return head;
}