按之字形顺序打印二叉树

题目描述

class Solution
{
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> res;
if(pRoot == NULL) return res;
int numOfPos = 0;
vector<TreeNode*> tmpStorage;
tmpStorage.push_back(pRoot);
while(tmpStorage.size())
{
vector<int> resLittle;
int number = tmpStorage.size();
for(int i = 0;i < number;i++)
{
resLittle.push_back(tmpStorage[i]->val);
}
res.push_back(resLittle);

vector<TreeNode*> tempNextPos;
if(numOfPos%2 == 0)
{
for(int i = number-1;i >= 0;i--)
{
if(tmpStorage[i]->right) tempNextPos.push_back(tmpStorage[i]->right);
if(tmpStorage[i]->left) tempNextPos.push_back(tmpStorage[i]->left);
}
}
else if(numOfPos%2 == 1)
{
for(int i = number-1;i >= 0;i--)
{
if(tmpStorage[i]->left) tempNextPos.push_back(tmpStorage[i]->left);
if(tmpStorage[i]->right) tempNextPos.push_back(tmpStorage[i]->right);
}
}
tmpStorage.clear();
for(int i = 0;i < tempNextPos.size();i++)
{
tmpStorage.push_back(tempNextPos[i]);
}
numOfPos++;
}
return res;
}

};

class Solution {
public:
vector<vector<int>> res;
vector<vector<int> > Print(TreeNode* pRoot)
{
if(pRoot == NULL)	return res;
vector<TreeNode*> storageNode;
storageNode.push_back(pRoot);
printHelper(storageNode,0);
return res;
}
void printHelper(vector<TreeNode*> storageNode,int num)
{
if(storageNode.empty()) return;
vector<TreeNode*> storageNodeTmp;
vector<int> storageNum;
for(int i = 0;i < storageNode.size();i++)
{
storageNum.push_back(storageNode[i]->val);
}
res.push_back(storageNum);
if(num%2 == 0)
{
for(int i = storageNode.size()-1;i >= 0;i--)
{
if(storageNode[i]->right) storageNodeTmp.push_back(storageNode[i]->right);
if(storageNode[i]->left) storageNodeTmp.push_back(storageNode[i]->left);
}
}
if(num%2 == 1)
{
for(int i = storageNode.size()-1;i >= 0;i--)
{
if(storageNode[i]->left) storageNodeTmp.push_back(storageNode[i]->left);
if(storageNode[i]->right) storageNodeTmp.push_back(storageNode[i]->right);
}
}
num++;
printHelper(storageNodeTmp,num);
}
};