标签:val vector back ret end temp false res 剑指offer
Q:请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
A:BFS,偶数层reverse
vector<vector<int> > Print(TreeNode *pRoot) {
vector<vector<int> > result;
if (pRoot == nullptr)
return result;
bool rever = false;
TreeNode *temp;
queue<TreeNode *> queue;
queue.push(pRoot);
int count = 1;
vector<int> temp0;
while (!queue.empty()) {
while (count-- != 0) {
temp = queue.front();
temp0.push_back(temp->val);
queue.pop();
if (temp->left)
queue.push(temp->left);
if (temp->right)
queue.push(temp->right);
}
count = queue.size();
if (!rever) {
rever = true;
} else {
reverse(temp0.begin(), temp0.end());
rever = false;
}
result.push_back(temp0);
temp0.clear();
}
return result;
}
Q:从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
A:BFS,比上面还简单,不用reverse(摊手)
vector<vector<int> > Print(TreeNode *pRoot) {
vector<vector<int> > result;
if (pRoot == nullptr)
return result;
bool rever = false;
TreeNode *temp;
queue<TreeNode *> queue;
queue.push(pRoot);
int count = 1;
vector<int> temp0;
while (!queue.empty()) {
while (count-- != 0) {
temp = queue.front();
temp0.push_back(temp->val);
queue.pop();
if (temp->left)
queue.push(temp->left);
if (temp->right)
queue.push(temp->right);
}
count = queue.size();
result.push_back(temp0);
temp0.clear();
}
return result;
}
剑指offer系列——59/60.按之字形顺序打印二叉树/把二叉树打印成多行
标签:val vector back ret end temp false res 剑指offer
原文地址:https://www.cnblogs.com/xym4869/p/12373256.html