描述
给定一个二叉树,返回该二叉树的之字形层序遍历,(第一层从左向右,下一层从右向左,一直这样交替)
例如:
给定的二叉树是{1,2,3,#,#,4,5}
该二叉树之字形层序遍历的结果是
[
[1],
[3,2],
[4,5]
]
示例1
输入: {1,2,3,#,#,4,5}
返回值: [[1],[3,2],[4,5]]
示例2
输入: {8,6,10,5,7,9,11}
返回值: [[8],[10,6],[5,7,9,11]]
示例3
输入: {1,2,3,4,5}
返回值: [[1],[3,2],[4,5]]
题解
题目描述:给定一颗二叉树,假设根节点为第一层,按照奇数层,从左到右打印,偶数层,从右到左打印。
方法:队列
层次遍历打印二叉树,用队列实现。
有一句话,我觉得说的特别好:做题=解法+模板,意思就是说,对于一道题目,首先明白正确的解法已经解决该问题70%,剩下的就直接套模板。
所以BFS的模板为:
1、如果不需要确定当前遍历到了哪一层,模板如下:
void bfs() {
vis[] = {0}; // or set
queue<int> pq(start_val);
while (!pq.empty()) {
int cur = pq.front(); pq.pop();
for (遍历cur所有的相邻节点nex) {
if (nex节点有效 && vis[nex]==0){
vis[nex] = 1;
pq.push(nex)
}
} // end for
} // end while
}
上述是伪代码,不仅可用于二叉树,可针对所有用BFS解题。
2、如果需要确定遍历到哪一层,模板如下:
void bfs() {
int level = 0;
vis[] = {0}; // or set
queue<int> pq(original_val);
while (!pq.empty()) {
int sz = pq.size();
while (sz--) {
int cur = pq.front(); pq.pop();
for (遍历cur所有的相邻节点nex) {
if (nex节点有效 && vis[nex] == 0) {
vis[nex] = 1;
pq.push(nex)
}
} // end for
} // end inner while
level++;
} // end outer while
}
此题跟“按层打印二叉树”,仅有一点区别,“按层打印二叉树”是每层都按照从左到右打印二叉树。
而此题是,按照奇数层,从左到右打印,偶数层,从右到左打印。
所以此题可直接套用模板,代码如下:
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> ret;
if (!pRoot) return ret;
queue<TreeNode*> q;
q.push(pRoot);
int level = 0;
while (!q.empty()) {
int sz = q.size();
vector<int> ans;
while (sz--) {
TreeNode *node = q.front();
q.pop();
ans.push_back(node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
++level;
if (!(level&1)) // 偶数层 反转一下
reverse(ans.begin(), ans.end());
ret.push_back(ans);
}
return ret;
}
};
时间复杂度:O(N^2)
空间复杂度:O(1), vecotr<vecotr> 是必须要开的,不算在额外空间里
js实现
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function Print(pRoot)
{
const res = [];
// write code here
if(pRoot === null){
return res;
}
const queue = [];
const stack = [];
queue.push(pRoot);
let layer = 1;
while(queue.length !== 0 || stack.length !== 0){
let row = [];
//奇数层 左->右遍历 队列存储
if(layer%2){
while(queue.length !==0 ){
const item = queue.pop();
row.push(item.val);
if(item.left !== null)stack.push(item.left);
if(item.right !== null)stack.push(item.right);
}
}else {
//偶数层,从右->左遍历 栈存储
while(stack.length !== 0) {
const item = stack.pop();
row.push(item.val);
if(item.right !== null)queue.push(item.right);
if(item.left !== null)queue.push(item.left);
}
}
layer++;
res.push(row);
}
return res;
}