模拟递归的过程,利用栈的特点来实现遍历。
我们增加一个结构体,用来标示当前的状态:printf/go 来完成前中后序的遍历。
struct Command
{
string s; //ptint/go两种状态
TreeNode* node;
Command(string s,TreeNode* node)
:s(s),node(node)
{}
};
前序遍历
struct Command
{
string s;
TreeNode* node;
Command(string s,TreeNode* node)
:s(s),node(node)
{}
};
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int >res;
if(root==NULL)
{
return res;
}
stack<Command> stack;
stack.push(Command("go",root));
while(!stack.empty())
{
Command command=stack.top();
stack.pop();
if(command.s=="print")
{
res.push_back(command.node->val);
}
else
{
if(command.node->right)
{
stack.push(Command("go",command.node->right));
}
if(command.node->left)
{
stack.push(Command("go",command.node->left));
}
stack.push(Command("print",command.node));//控制入栈与访问的先后顺序
}
}
return res;
}
中序遍历
struct Command
{
string s;
TreeNode* node;
Command(string s,TreeNode* node)
:s(s),node(node)
{}
};
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int >res;
if(root==NULL)
{
return res;
}
stack<Command> stack;
stack.push(Command("go",root));
while(!stack.empty())
{
Command command=stack.top();
stack.pop();
if(command.s=="print")
{
res.push_back(command.node->val);
}
else
{
if(command.node->right)
{
stack.push(Command("go",command.node->right));
}
stack.push(Command("print",command.node));
if(command.node->left)
{
stack.push(Command("go",command.node->left));
}
}
}
return res;
}
后序遍历
struct Command
{
string s;
TreeNode* node;
Command(string s,TreeNode* node)
:s(s),node(node)
{}
};
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int >res;
if(root==NULL)
{
return res;
}
stack<Command> stack;
stack.push(Command("go",root));
while(!stack.empty())
{
Command command=stack.top();
stack.pop();
if(command.s=="print")
{
res.push_back(command.node->val);
}
else
{ stack.push(Command("print",command.node));
if(command.node->right)
{
stack.push(Command("go",command.node->right));
}
if(command.node->left)
{
stack.push(Command("go",command.node->left));
}
}
}
return res;
}