分析:其实就是一个bfs,只不过输出的时候,第一行按照从左到右,第二行从右到左,第三行和第一行同理,依次类推
注意构造函数,析构函数和防御性编程
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
const int maxn = 100+5;
class Solution {
public:
Solution()
{
}
~Solution()
{
}
void bfs(TreeNode* pRoot,vector<vector<int> >&vec)
{
vector<int>G[maxn];
queue<pair<TreeNode*,int> > pq;
while(!pq.empty()) pq.pop();
pq.push(make_pair(pRoot,1));
while(!pq.empty())
{
pair<TreeNode*,int>T_node;
T_node = pq.front();
pq.pop();
G[T_node.second].push_back(T_node.first->val);
if(T_node.first->left!=nullptr) {
pq.push(make_pair(T_node.first->left,T_node.second+1));
}
if(T_node.first->right!=nullptr) {
pq.push(make_pair(T_node.first->right,T_node.second+1));
}
}
vector<int>path;
path.clear();
for(int i=1;i<maxn;i++)
{
if(G[i].size()==0) break;
path.clear();
if(!(i&1)) {
for(int j = G[i].size()-1;j>=0;j--)
path.push_back(G[i][j]);
}
else {
for(int j=0;j<G[i].size();j++)
path.push_back(G[i][j]);
}
vec.push_back(path);
}
}
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int> > solve;
solve.clear();
if(pRoot==nullptr) return solve;
bfs(pRoot,solve);
return solve;
}
};