前序遍历144

  • 思路:栈是先进后出的,前序遍历是中左右;因此入队时先入右再入左

    1. class Solution {
    2. public:
    3. vector<int> preorderTraversal(TreeNode* root) {
    4. vector<int> res;
    5. if (root == nullptr) return res;
    6. stack<TreeNode*> st;
    7. st.push(root);
    8. while (!st.empty()) {
    9. int len = st.size();
    10. for (int i = 0; i < len; ++i) {
    11. TreeNode* node = st.top(); st.pop();
    12. res.push_back(node->val);
    13. if (node->right) st.push(node->right);
    14. if (node->left) st.push(node->left);
    15. }
    16. }
    17. return res;
    18. }
    19. };

中序遍历94

  • 思路:左中右;先走到最左边,然后操作,然后往右走
  • 注意:该遍历比较反常规,需要好好看一下

    1. class Solution {
    2. public:
    3. vector<int> inorderTraversal(TreeNode* root) {
    4. vector<int> res;
    5. if (root == nullptr) return res;
    6. stack<TreeNode*> st;
    7. TreeNode* cur = root;
    8. while (cur != nullptr || !st.empty()) {
    9. if (cur != nullptr) {
    10. st.push(cur);
    11. cur = cur->left; // 左
    12. }else {
    13. cur = st.top(); st.pop();
    14. res.push_back(cur->val); // 中
    15. cur = cur->right; // 右
    16. }
    17. }
    18. return res;
    19. }
    20. };

后序遍历145

  • 思路:后序遍历是左右中;操作后,先入队左,再入队右,最后对整个数组进行翻转

    1. class Solution {
    2. public:
    3. vector<int> postorderTraversal(TreeNode* root) {
    4. vector<int> res;
    5. if (root == nullptr) return res;
    6. stack<TreeNode*> st;
    7. st.push(root);
    8. while (!st.empty()) {
    9. int len = st.size();
    10. for (int i = 0; i < len; i++) {
    11. TreeNode* node = st.top(); st.pop();
    12. res.push_back(node->val);
    13. if (node->left) st.push(node->left);
    14. if (node->right) st.push(node->right);
    15. }
    16. }
    17. reverse(res.begin(), res.end());
    18. return res;
    19. }
    20. };