## 1 先序遍历

``````class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
//设置栈和存储结果的vector
stack<TreeNode*> s;
vector<int> ans;
//使用根节点初始化游标节点
TreeNode* t = root;
//当游标节点非空或者栈非空时
while(t || !s.empty()){
if(t){
//如果游标节点非空
ans.push_back(t->val);
//游标节点入栈
s.push(t);
//更新游标节点
t = t->left;
}else{
//使用父节点的右孩子更新游标节点
t = s.top()->right;
//栈顶元素出栈
s.pop();
}//if
}//while
return ans;
}
};
``````

## 2 中序遍历

``````class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
//设置栈和存储结果的vector
stack<TreeNode*> s;
vector<int> ans;
//使用根节点初始化游标节点
TreeNode* t = root;
//当游标节点非空或者栈非空时
while(t || !s.empty()){
//遍历到最左边的叶结点
while(t){ s.push(t); t = t->left;}
if(!s.empty()){
//输出栈顶元素
ans.push_back(s.top()->val);
//使用栈顶元素的右指针更新游标指针
t = s.top()->right;
//栈顶元素出栈
s.pop();
}//if
}//while
return ans;
}
};
``````
``````class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
//设置栈和存储结果的vector
stack<TreeNode*> s;
vector<int> ans;
//使用根节点初始化游标节点
TreeNode* t = root;
//当游标节点非空或者栈非空时
while(t || !s.empty()){
//遍历到最左边的叶结点
if(t){
s.push(t);
t = t->left;
}else{
//输出栈顶元素
ans.push_back(s.top()->val);
//使用栈顶元素的右指针更新游标指针
t = s.top()->right;
//栈顶元素出栈
s.pop();
}//if
}//while
return ans;
}
};
``````

## 3 后序遍历

``````// //////// 严格按照后序遍历的定义
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
vector<int> v;
stack<TreeNode*> s_stack;

TreeNode *node = root;
TreeNode *lastVisitNode = NULL;
while (!s_stack.empty() || node != NULL){
if (node != NULL){
// keep going the left
s_stack.push(node);
node = node->left;
}
else{
TreeNode *n = s_stack.top();
// left way is finsised, keep going to the right way
if (n->right != NULL && lastVisitNode != n->right){
node = n->right;
}
else{
// both left and right has been accessed.
s_stack.pop();
v.push_back(n->val);
//更新上次被访问的节点
lastVisitNode = n;
}
}
}
return v;
}
};
``````