双端队列
一. 定义
双端队列支持前后双端插入元素、弹出、删除元素
deque<object_type>deq
常用函数:
1 2 3 4 5 6 7 8 9 10 11 12 13
| push_back();
push_front();
TreeNode *node = deq.front();
pop_front();
pop_back();
back();
front();
|
二、例题
二叉树的镜像
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
class Solution { public: TreeNode* mirrorTree(TreeNode* root) { deque<TreeNode*>deq; if(root == NULL) { return NULL; } deq.push_back(root); while(!deq.empty()) { TreeNode *node = deq.front(); deq.pop_front(); if(node->left) { deq.push_front(node->left); } if(node->right) { deq.push_front(node->right); } TreeNode *tmp = node->left; node->left = node->right; node->right = tmp; }
return root; } };
|
剑指 Offer 32 - III. 从上到下打印二叉树 III
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>>ans; if(root == NULL) { return ans; } queue<TreeNode*>que; que.push(root); int level = 0; while(!que.empty()) { int size = que.size(); deque<int>deq; for(int i = 0; i < size; i++) { TreeNode *node = que.front(); que.pop(); if(level % 2 == 0) { deq.push_back(node->val); } else { deq.push_front(node->val); } if(node->left) { que.push(node->left); } if(node->right) { que.push(node->right); } } ans.emplace_back(deq.begin(), deq.end()); level++; } return ans; } };
|