资料:
栈stack常用的函数:
【C++】STL——stack的介绍和使用、stack的push和pop函数介绍和使用、stack的其他成员函数_c++的pop_鳄鱼麻薯球的博客-CSDN博客
empty() 检测stack是否为空
size() 返回stack中元素的个数
top() 返回栈顶元素的引用
push() 将元素val压入stack中
pop() 将stack中尾部的元素弹出
自己写的:
①用队列和栈交替使用,伪代码:
奇数行用队列{
下一行的元素放到栈里面;
}偶数行用栈{
下一行的元素放到队列里面;
}
不行,因为:
第n行,栈遍历,(二叉树的角度)是从右往左遍历,第n+1行,(二叉树的角度)是从右往左进入队列。
第n+1行,队列遍历,二叉树的角度)也变成从右往左遍历了。
②考虑“之”字形:
上一行最后遍历最右边的,下一行从最右边开始;
上一行最后遍历最左边的,下一行从最左边开始;
综上,都用栈,代码如下(通过):
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pRoot TreeNode类
* @return int整型vector<vector<>>
*/
vector<vector<int> > Print(TreeNode* pRoot) {
// write code here
vector<vector<int>> res;
if (pRoot == NULL)
return res;
stack<TreeNode*> s; // 栈: 先入后出
s.push(pRoot);
int flag = 0;
while (!s.empty()) {
vector<int> row;
stack<TreeNode*> s2; // 不同于队列queue,还需要一个栈stack s2
int m = s.size();
for (int i = 0; i < m; i++) {
TreeNode* cur = s.top();
row.push_back(cur->val);
if (flag == 0) {
if (cur->left)
s2.push(cur->left);
if (cur->right)
s2.push(cur->right);
s.pop();
} else {
if (cur->right)
s2.push(cur->right);
if (cur->left)
s2.push(cur->left);
s.pop();
}
}
res.push_back(row);
flag = 1 - flag; // 不是放在for循环里面,而是while循环里面
s = s2;
}
return res;
}
};
模板:
遍历过程和BM26(正常的层序遍历)一样,最后用flag对偶数行翻转一下。