一、题目描述(Again !)
题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
思路:
定义两个栈,分别用来保存奇数层结点和偶数层结点,奇数层结点 从左到右打印(所以它们要从右到左进栈),偶数层结点从右到左打印(所以它们要从左到右进栈)。
vector<vector<int> > Print(TreeNode* pRoot) {
stack<TreeNode*> st[2];
vector<vector<int> > res;
vector<int> path;
if(pRoot==NULL)
return res;
st[0].push(pRoot);
TreeNode* outputNode=NULL;
int curr=0;
while(!st[0].empty() || !st[1].empty())
{
outputNode=st[curr].top();
st[curr].pop();
path.push_back(outputNode->val);
if(curr==0)
{
if(outputNode->left!=NULL)
st[!curr].push(outputNode->left);
if(outputNode->right!=NULL)
st[!curr].push(outputNode->right);
}
else
{
if(outputNode->right!=NULL)
st[!curr].push(outputNode->right);
if(outputNode->left!=NULL)
st[!curr].push(outputNode->left);
}
if(st[curr].empty())
{
res.push_back(path);
path.clear();
curr=!curr;
}
}
return res;
}
二、
题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int> > res;
if(pRoot==NULL)
return res;
vector<int> level;
queue<TreeNode*> que;
que.push(pRoot);
int toBePrint=1;//当前层还有多少个结点待打印
int nextLevel=0;//下一行有多少个结点
TreeNode* tmp=NULL;
while(!que.empty())
{
tmp=que.front();
que.pop();
toBePrint--;
level.push_back(tmp->val);
if(tmp->left!=NULL)
{
que.push(tmp->left);
nextLevel++;
}
if(tmp->right!=NULL)
{
que.push(tmp->right);
nextLevel++;
}
if(toBePrint==0)
{
res.push_back(level);
level.clear();
toBePrint=nextLevel;
nextLevel=0;
}
}
return res;
}