#include <string>
#include <iostream>
#include <vector>
#include <cstring>
#include <stack>
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>> ret;
if(pRoot==NULL)
return ret;
stack<TreeNode*> s1;
stack<TreeNode*> s2;
bool flag=true;
s1.push(pRoot);
while(!s1.empty()||!s2.empty())
{
if(flag)//从左边到右访问
{
vector<int> cur;
while(!s1.empty())
{
TreeNode *temp=s1.top();
s1.pop();
cur.push_back(temp->val);
if(temp->left!=NULL)
s2.push(temp->left);
if(temp->right!= NULL)
s2.push(temp->right);
}
ret.push_back(cur);
flag=!flag;
}else//从右到左边访问
{
vector<int> cur;
while(!s2.empty())
{
TreeNode *temp=s2.top();
s2.pop();
cur.push_back(temp->val);
if(temp->right!=NULL)
s1.push(temp->right);
if(temp->left!=NULL)
s1.push(temp->left);
}
ret.push_back(cur);
flag=!flag;
}
}
return ret;
}
};
按照之字形打印二叉树
最新推荐文章于 2024-02-18 10:31:45 发布