题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
解题思路:
队列方便与从左往右遍历,栈方便与从右往左遍历。所以这道题只需把前一题的栈结构改为队列,然后存储左右顺序改一下
参考代码:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stack>
#include <queue>
#include <list>
#include <unordered_map>
using namespace std;
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> > my_res;
vector<int> my_temp;
if (pRoot == NULL)
return my_res;
int layer = 1;
queue<TreeNode*> my_odd; //奇数
queue<TreeNode*> my_even; //偶数
my_odd.push(pRoot);
while (!my_odd.empty() || !my_even.empty())
{
if (layer%2 == 1) //奇数层
{
while (!my_odd.empty())
{
my_temp.push_back(my_odd.front()->val);
cout<<"odd:"<<my_odd.front()->val<<endl;
TreeNode* middle = my_odd.front();
if (middle->left != NULL)
my_even.push(middle->left);
if (middle->right != NULL)
my_even.push(middle->right);
my_odd.pop();
}
if (!my_temp.empty())
{
my_res.push_back(my_temp);
my_temp.clear();
layer++;
}
} else{ //偶数层
while (!my_even.empty())
{
my_temp.push_back(my_even.front()->val);
cout<<"even:"<<my_even.front()->val<<endl;
TreeNode* middle = my_even.front();
if (middle->left != NULL)
my_odd.push(middle->left);
if (middle->right != NULL)
my_odd.push(middle->right);
my_even.pop();
}
if (!my_temp.empty())
{
my_res.push_back(my_temp);
my_temp.clear();
layer++;
}
}
}
return my_res;
}
};
int main() {
Solution solution;
TreeNode TreeNode1(1);
TreeNode TreeNode2(2);
TreeNode TreeNode3(3);
TreeNode TreeNode4(4);
TreeNode TreeNode5(5);
TreeNode TreeNode6(6);
TreeNode TreeNode7(7);
TreeNode1.left = &TreeNode2;
TreeNode1.right = &TreeNode3;
TreeNode2.left = &TreeNode4;
TreeNode2.right = &TreeNode5;
TreeNode3.left = &TreeNode6;
TreeNode3.right = &TreeNode7;
TreeNode4.left = NULL;
TreeNode4.right = NULL;
TreeNode5.left = NULL;
TreeNode5.right = NULL;
TreeNode6.left = NULL;
TreeNode6.right = NULL;
TreeNode7.left = NULL;
TreeNode7.right = NULL;
TreeNode* my_head = &TreeNode1;
solution.Print(my_head);
return 0;
}