二叉树的前中后序遍历(利用栈实现迭代法)

二叉树的迭代遍历

前序遍历

class Solution {
public:
    vector preorderTraversal(TreeNode* root) {
        stack st;
        vector result;
        st.push(root);
        while (!st.empty()) {
            TreeNode* top = st.top();
            st.pop();
            if (top == nullptr)continue;
            result.push_back(top->val);
            st.push(top->right);
            st.push(top->left);
        }
        return result;
    }
};

中序遍历

class Solution {
public:
    vector inorderTraversal(TreeNode* root) {
        stack st;
        vector result;
        TreeNode* ptr = root;
        while (ptr != nullptr || !st.empty()) {
            if (ptr != nullptr) {
                st.push(ptr);
                ptr = ptr->left;
            }
            else {
                ptr = st.top();
                st.pop();
                result.push_back(ptr->val);
                ptr = ptr->right;
            }
        }
        return result;
    }
};

后序遍历

class Solution {
public:
    vector postorderTraversal(TreeNode* root) {
        vector result;
        stack st;
        st.push(root);
        while (!st.empty()) {
            TreeNode* ptr = st.top();
            st.pop();
            if (ptr == nullptr)continue;
            result.push_back(ptr->val);
            st.push(ptr->left);
            st.push(ptr->right);
        }
        reverse(result.begin(), result.end());
        return result;
    }
};

你可能感兴趣的:(数据结构与算法,算法,leetcode,二叉树)