先序遍历
中序遍历
迭代版1:
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*> S;
vector<int> result;
TreeNode *cur = root;
while(true){
if(cur != NULL){
S.push(cur);
cur = cur->left;
}else if(!S.empty()){
cur = S.top(); S.pop();
result.push_back(cur->val);
cur = cur->right;
}else{
break;
}
}
return result;
}
};
后序遍历:
迭代版1:
stack<TreeNode*> S; //后续遍历栈
TreeNode *cur = root;
S.push(cur);
while(!S.empty()){
if(S.top()->left != cur && S.top()->right != cur){ //进入兄弟节点
gotoHLVFL(S);
}
//访问节点
cur = S.top(); S.pop();
//visit(cur)
}
void gotoHLVFL(stack<TreeNode*> &S){
TreeNode *cur;
while((cur = S.top()) != NULL){
if(cur->left != NULL){
if(cur->right != NULL) S.push(cur->right);
S.push(cur->left);
// cur = cur->left;
}else{
S.push(cur->right);
// cur = cur->right;
}
}
S.pop();
}
vector<int> postOrder(TreeNode *root)
{
vector<int> res;
if(root == NULL) return res;
TreeNode *p = root;
stack<TreeNode *> sta;
sta.push(p);
sta.push(p);
while(!sta.empty())
{
p = sta.top(); sta.pop();
if(!sta.empty() && p==sta.top())
{
if(p->right) sta.push(p->right), sta.push(p->right);
if(p->left) sta.push(p->left), sta.push(p->left);
}
else
res.push_back(p->val);
}
return res;
}
对于每个节点,都压入两遍,在循环体中,每次弹出一个节点赋给p,如果p仍然等于栈的头结点,说明p的孩子们还没有被操作过,应该把它的孩子们加入栈中,否则,访问p。也就是说,第一次弹出,将p的孩子压入栈中,第二次弹出,访问p。