53.按之字形顺序打印二叉树
题目内容:
代码及思路:
由于不同行打印的顺序不同,因此我们可以设置两个栈来分别交替存放奇偶层的结点值。
奇数层:从左到右
偶数层:从右到左
#include<iostream>
#include<vector>
#include<stack>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
};
class Solution {
public:
void buildtree(TreeNode** root)
{
int temp;
cin >> temp;
if (temp == 0)
{
(*root)->val = 0;
(*root) = nullptr;
return;
}
else
{
(*root)->val = temp;
(*root)->left = new TreeNode;
buildtree(&(*root)->left);
(*root)->right = new TreeNode;
buildtree(&(*root)->right);
}
}
vector<vector<int>> Print(TreeNode* pRoot)
{
vector<vector<int>> res;
int depth = 1;
//对无效输入进行判断
if (pRoot == nullptr)
return res;
//可以使用两个堆栈分别存放奇偶层的结点数
stack<TreeNode*> stack1;
stack<TreeNode*> stack2;
stack1.push(pRoot);
//对两个栈分别放入奇数和偶数行的树结点
while (!stack1.empty() || !stack2.empty())
{
if (!stack1.empty())
{
vector<int> numbers;
while (!stack1.empty()) //stack1存放的是奇数层的树结点
{
TreeNode* pNode = stack1.top();
stack1.pop();
numbers.push_back(pNode->val);
if (pNode->left) //偶数层因为是从右到左打印,因此存放的时候从左向右存放
stack2.push(pNode->left);
if (pNode->right)
stack2.push(pNode->right);
}
res.push_back(numbers);
}
if (!stack2.empty())
{
vector<int> numbers;
while (!stack2.empty()) //stack2存放的是偶数层的树结点
{
TreeNode*pNode = stack2.top();
stack2.pop();
numbers.push_back(pNode->val);
if (pNode->right)
stack1.push(pNode->right);
if (pNode->left)
stack1.push(pNode->left);
}
res.push_back(numbers);
}
}
return res;
}
};
int main()
{
Solution* object = new Solution();
TreeNode* root = new TreeNode;
object->buildtree(&root);
vector<vector<int>> res;
res = object->Print(root);
for (int i = 0; i < res.size(); i++)
{
res.resize(res.size());
for (int j = 0; j < res[i].size(); j++)
{
cout << res[i][j] << endl;
}
}
}