二叉树的后序遍历--迭代

使用两个栈来协助完成二叉树的遍历操作。
不难发现,如果我们以“根->右->左”的顺序遍历二叉树,将结果压进栈中,弹栈的时候顺序就是“左->右->根”,也就是后序遍历的结果了。
而“根->右->左”的遍历顺序和先序遍历很像(先序遍历是“根->左->右”)

用stack1协助,对每个结点依次将“根->右->左”的顺序入栈,最后将遍历结果保存到stack2中

依次弹出stack2中的元素即为二叉树的后序遍历结果

class Solution {
  public:
      vector<int> postorderTraversal(TreeNode* root) {
          vector<int>res;
           if (root == NULL)
              return res;
          //利用stack1前序遍历二叉树的结点(根、右、左)
          stack<TreeNode*>stack1;
          // //再把前序遍历的结果保存在stack2
          stack<TreeNode*>stack2;
          stack1.push(root);
          while (!stack1.empty()) {
              TreeNode* x = stack1.top();
              stack1.pop();
              stack2.push(x);
              if (x->left != NULL) {
                  stack1.push(x->left);
              }
              if (x->right != NULL) {
                  stack1.push(x->right);
              }
          }
          //前序遍历出栈之后就是后序遍历的结果
          while (!stack2.empty()) {
              TreeNode* temp = stack2.top();
              stack2.pop();
              res.push_back(temp->val);
          }
          return res;
      }
  };
原文地址:https://www.cnblogs.com/-citywall123/p/12893526.html