二叉树层序遍历 | 按之字形打印二叉树
按层打印
宽度优先搜索。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> ret;
if (pRoot == NULL) {
return ret;
}
queue<TreeNode*> q;
q.push(pRoot);
while (!q.empty()) {
int len = q.size();
vector<int> tmp(len);
for (int i = 0; i < len; ++i) {
TreeNode* cur = q.front(); q.pop();
tmp[i] = cur->val;
if (cur->left) q.push(cur->left);
if (cur->right) q.push(cur->right);
}
ret.push_back(tmp);
}
return ret;
}
};
之字形打印
BFS做一下修改。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> ret;
if (pRoot == NULL) {
return ret;
}
vector<TreeNode*> q;
q.push_back(pRoot);
bool sign = true; // sign为true从左到右,否则从右到左
for (int i = 0; i < q.size(); ) {
int start = i, end = q.size() - 1;
vector<int> tmp(end-start+1);
int k = 0;
for (int j = start; j <= end; ++j) {
tmp[k++] = q[j]->val;
if (q[j]->left) q.push_back(q[j]->left);
if (q[j]->right) q.push_back(q[j]->right);
}
if (!sign) std::reverse(tmp.begin(), tmp.end());
ret.push_back(tmp);
i = end + 1;
sign = !sign;
}
return ret;
}
};