二叉树的非递归遍历(栈)

struct TreeNode
{
    int val;
    TreeNode *left,*right;
    TreeNode(int x):val(x),left(0),right(0){}
};

//前序遍历
vector<int> preorderTraversal(TreeNode *root) 
{
    vector<int> res;
    stack<TreeNode *> s;
    TreeNode *p=root;
    while(!s.empty()||p) 
    {
        while(p)
        {
            res.push_back(p->val);
            s.push(p);
            p=p->left;
        }
        if(!s.empty())
        {
            p=s.top();
            s.pop();
            p=p->right;
        }
    }
    return res;
}

vector<int> preorderTraversal(TreeNode *root) 
{
    vector<int> res;
    stack<TreeNode *> s;
    TreeNode *p=root;
    while(!s.empty()||p) 
    {
        if(p)
        {
            res.push_back(p->val);
            s.push(p);
            p=p->left;
        }
        else
        {
            p=s.top();
            s.pop();
            p=p->right;
        }
    }
    return res;
}

//中序遍历
vector<int> inorderTraversal(TreeNode *root) 
{
    vector<int> res;
    stack<TreeNode *> s;
    TreeNode *p=root;
    while(!s.empty()||p) 
    {
        while(p)
        {
            s.push(p);
            p=p->left;
        }
        if(!s.empty())   
        {
            p=s.top();
            s.pop();
            res.push_back(p->val);
            p=p->right;
        }
    }
    return res;
}

vector<int> inorderTraversal(TreeNode *root) 
{
    vector<int> res;
    stack<TreeNode *> s;
    TreeNode *p=root;
    while(!s.empty()||p) 
    {
        if(p)
        {
            s.push(p);
            p=p->left;
        }
        else   
        {
            p=s.top();
            s.pop();
            res.push_back(p->val);
            p=p->right;
        }
    }
    return res;
}

//后序遍历
vector<int> postorderTraversal(TreeNode *root) 
{
    vector<int> res;
    stack<TreeNode *> s;
    TreeNode *cur=root,*prev=0;
    while(cur)  
    {  
        s.push(cur);  
        cur=cur->left;  
    }
    while(!s.empty())  
    {   
        cur=s.top();  
        s.pop();    
        if(!cur->right||cur->right==prev)  
        {  
            res.push_back(cur->val); 
            prev=cur;  
        }  
        else  
        {    
            s.push(cur);    
            cur=cur->right;  
            while(cur)  
            {  
                s.push(cur);  
                cur=cur->left;  
            }  
        }  
    }  
    return res;
}

http://blog.csdn.net/zhangxiangdavaid/article/details/37115355

你可能感兴趣的:(二叉树的非递归遍历(栈))