GH1995 / leetcode-test-and-run

方便 leetcode 刷题的小工具
GNU General Public License v2.0
0 stars 0 forks source link

二叉树非递归遍历 #71

Open GH1995 opened 5 years ago

GH1995 commented 5 years ago
class Solution {
public:
    vector<int> preorderTraversal(TreeNode *root) {
        vector<int> result;
        stack<TreeNode *> stk;

        auto cur = root;
        while (cur || !stk.empty()) {
            while (cur) {
                result.push_back(cur->val);
                stk.push(cur);
                cur = cur->left;
            }
            cur = stk.top(), stk.pop();
            cur = cur->right;
        }
        return result;
    }

    vector<int> inorderTraversal(TreeNode *root) {
        vector<int> result;
        stack<TreeNode *> stk;

        auto cur = root;
        while (cur || !stk.empty()) {
            while (cur) {
                stk.push(cur);
                cur = cur->left;
            }
            cur = stk.top(), stk.pop();
            result.push_back(cur->val);
            cur = cur->right;
        }

        return result;
    }

    vector<int> postorderTraversal(TreeNode *root) {
        vector<int> result;
        stack<TreeNode *> stk;

        auto cur = root;
        while (!stk.empty() || cur) {
            if (cur) {
                stk.push(cur);
                result.insert(result.begin(), cur->val);
                cur = cur->right;
            } else {
                cur = stk.top();
                stk.pop();
                cur = cur->left;
            }
        }

        return result;
    }
};