class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> stack;
TreeNode * r = NULL;//记录最近访问过的节点初始值设为NULL
TreeNode * p = root;
while(p||!stack.empty()){
if(p){
stack.push(p);
p= p->left;
}else{
p = stack.top();
p = p->right;
if(p && p!= r){
stack.push(p);
p = p->left;
}else{//如果无右子树或者右子树已经被访问过 栈顶元素出栈直接访问
p = stack.top();
stack.pop();
res.push_back(p->val);
r = p;
p = NULL;
}
}
}
return res;
}
};
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> stack;
stack.push(root);
while(!stack.empty()){
TreeNode* peer = stack.top();
if(peer){
if(peer->left){
stack.push(peer->left);
continue;
}else{
stack.pop();//若无左子树 出栈
res.push_back(peer->val);//访问之
while(!stack.empty()&&!(peer->right)){
peer = stack.top();
stack.pop();
res.push_back(peer->val);
}
if(peer->right){
stack.push(peer->right);
}
}
}
}
return res;
}
}