题目1:不分行从上到下打印二叉树
从上到下打印出二叉树的每个节点,同一层的结点按照从左到右的顺序打印。
分析: 使用队列实现
class Solution {
public:
queue<TreeNode*> queue_help;
vector<int> PrintFromTopToBottom(TreeNode* root) {
vector<int> result;
if (root == nullptr) return result;
queue_help.push(root);
while(!queue_help.empty()){
TreeNode* temp = queue_help.front();
queue_help.pop();
result.push_back(temp->val);
if (temp->left != nullptr) queue_help.push(temp->left);
if (temp->right != nullptr) queue_help.push(temp->right);
}
return result;
}
};
题目2: 分行从上到下打印二叉树
分析:引入两个变量,toBePrinted 本层记录本层还要打印的结点的个数
nextLevel 记录下一层中的需要打印的结点的个数
class Solution {
public:
queue<TreeNode*> queue_help;
void PrintFromTopToBottomInRow(TreeNode* root) {
if (root == nullptr) return;
queue_help.push(root);
int toBePrinted = 1;
int nextLevel = 0;
while(!queue_help.empty()){
TreeNode* temp = queue_help.front();
queue_help.pop();
cout << temp->val;
toBePrinted--;
if (temp->left != nullptr){
queue_help.push(temp->left);
nextLevel++;
}
if (temp->right != nullptr){
queue_help.push(temp->right);
nextLevel++;
}
if (toBePrinted == 0){
cout << "\n";
toBePrinted = nextLevel;
nextLevel = 0;
}
}
}
};
题目3:之字形打印二叉树
实现一个函数按照之字形顺序打印二叉树。即第一行按照从左到右的
顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右
的顺序打印,其他依次推类。
分析: 我的想法是搞一个stack_help, 在偶数行先将结点放进stack中,奇数行直接打印
class Solution {
public:
queue<TreeNode*> queue_help;
stack<int> stack_help;
void PrintFromTopToBottomInRowWithZhi(TreeNode* root) {
if (root == nullptr) return;
queue_help.push(root);
int toBePrinted = 1;
int nextLevel = 0;
bool isodd = true; //记录当前是奇数行还是偶数行
while(!queue_help.empty()){
TreeNode* temp = queue_help.front();
queue_help.pop();
// 如果是奇数层的话直接输出
if (isodd)
{
cout << temp->val << " ";
toBePrinted--;
}
// 如果是偶数层需要先放到stack_help中
else
{
stack_help.push(temp->val);
toBePrinted--;
}
if (temp->left != nullptr){
queue_help.push(temp->left);
nextLevel++;
}
if (temp->right != nullptr){
queue_help.push(temp->right);
nextLevel++;
}
if (toBePrinted == 0)
{
toBePrinted = nextLevel;
nextLevel = 0;
if (isodd) isodd = false;
else
{
isodd = true;
while(!stack_help.empty()) {
cout << stack_help.top() << " ";
stack_help.pop();
}
}
cout << "\n";
}
}
}
};