目录
103. 二叉树的锯齿形层次遍历
使用deque的
front(), back();
push_front(), push_back();
pop_front(), pop_back().
前取后放,后取前放。
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> ans;
if (!root) return ans;
deque<TreeNode*> que;
que.push_back(root);
bool zigzag = true;
TreeNode* tmp;
while (!que.empty()) {
int Size = que.size();
vector<int> tmp_vec;
while (Size) {
if (zigzag) { // 前取后放 FIFO
tmp = que.front();
que.pop_front();
if (tmp->left) que.push_back(tmp->left); // 下一层顺序存放至尾
if (tmp->right) que.push_back(tmp->right);
} else { // 后取前放 FILO
tmp = que.back();
que.pop_back();
if (tmp->right) que.push_front(tmp->right); // 下一层逆序存放至首
if (tmp->left) que.push_front(tmp->left);
}
tmp_vec.push_back(tmp->val);
--Size;
}
zigzag = !zigzag;
ans.push_back(tmp_vec);
}
return ans;
}
};
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
if (root == null) {
return new ArrayList<List<Integer>>();
}
List<List<Integer>> results = new ArrayList<List<Integer>>();
// add the root element with a delimiter to kick off the BFS loop
LinkedList<TreeNode> node_queue = new LinkedList<TreeNode>();
node_queue.addLast(root);
node_queue.addLast(null);
LinkedList<Integer> level_list = new LinkedList<Integer>();
boolean is_order_left = true;
while (node_queue.size() > 0) {
TreeNode curr_node = node_queue.pollFirst();
if (curr_node != null) {
if (is_order_left)
level_list.addLast(curr_node.val);
else
level_list.addFirst(curr_node.val);
if (curr_node.left != null)
node_queue.addLast(curr_node.left);
if (curr_node.right != null)
node_queue.addLast(curr_node.right);
} else {
// we finish the scan of one level
results.add(level_list);
level_list = new LinkedList<Integer>();
// prepare for the next level
if (node_queue.size() > 0)
node_queue.addLast(null);
is_order_left = !is_order_left;
}
}
return results;
}
}
150.逆波兰表达式求值
给定一个表达式的后序遍历,用栈求解即可
int evalRPN(vector<string>& tokens) {
stack<int> temp;
for(int i=0;i<tokens.size();i++)
{
if(tokens[i].size()==1&&(tokens[i][0]=='+'||tokens[i][0]=='-'||tokens[i][0]=='*'||tokens[i][0]=='/'))
{
int temp1=temp.top();
temp.pop();
int temp2=temp.top();
temp.pop();
//cout<<"temp1:"<<temp1<<'.'<<"temp2:"<<temp2<<endl;
if(tokens[i][0]=='+')
temp.push(temp1+temp2);
else if(tokens[i][0]=='-')
temp.push(temp2-temp1);
else if(tokens[i][0]=='*')
temp.push(temp1*temp2);
else
temp.push(temp2/temp1);
}
else
{
temp.push(atoi(tokens[i].c_str()));
}
}
return temp.top();
}