[树] 前序,中序,后序的非递归写法

前序遍历:

class Solution {
public:

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

 

中序遍历:

class Solution {
public:
    vector<int> res;
    vector<int> inorderTraversal(TreeNode* root) {
        stack<TreeNode*> sta;
        TreeNode* p = root;
        while(p)
        {
            sta.push(p);
            p = p->left;
        }
        while(!sta.empty())
        {
            TreeNode* p = sta.top();
            sta.pop();
            res.push_back(p->val);
            TreeNode* cur = p->right;
            while(cur)
            {
                sta.push(cur);
                cur = cur->left;
            }
            
        }
        return res;
    }
};

后序遍历:

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        if(!root) return res;
        stack<TreeNode*> sta;
        sta.push(root);
        while(!sta.empty())
        {
            TreeNode* p = sta.top();sta.pop();
            if(p->left) sta.push(p->left);
            if(p->right) sta.push(p->right);
            res.push_back(p->val);
        }
        reverse(res.begin(), res.end());
        return res;
    }
};

 

posted @ 2019-08-11 17:53  fish1996  阅读(344)  评论(0)    收藏  举报