递归虽然简单具有可读性,但同时具有栈溢出、重复计算、函数调用开销的缺点,在工程实现上,有些地方需要用迭代来替代递归。
    二叉树的Moris遍历又称二叉树的非递归遍历:前序和后序可以看成是一个Moris框架,中序算作另一种框架。
    前序Moris:(中,左,右)

    1. vector<int> preMoris(TreeNode* root){
    2. vector<int> ret;
    3. if(root==nullptr){
    4. return ret;
    5. }
    6. stack<TreeNode*> stk;
    7. stk.push(root);
    8. while(stk.empty()==false){
    9. TreeNode* cur=stk.top();
    10. stk.pop();
    11. ret.emplace_back(cur->val);
    12. if(cur->right){
    13. stk.push(cur->right);
    14. }
    15. if(cur->left){
    16. stk.push(cur->left);
    17. }
    18. }
    19. return ret;
    20. }

    后序Moris遍历:修改前序Moris达成(中,右,左)-reverse>(左,右,中)即后序

    1. vector<int> postMoris(TreeNode* root){
    2. vector<int> ret;
    3. if(root==nullptr){
    4. return ret;
    5. }
    6. stack<TreeNode*> stk;
    7. stk.push(root);
    8. while(stk.empty()==false){
    9. TreeNode* cur=stk.top();
    10. stk.pop();
    11. ret.emplace_back(cur->val);
    12. if(cur->left){
    13. stk.push(cur->left);
    14. }
    15. if(cur->right){
    16. stk.push(cur->right);
    17. }
    18. }
    19. reverse(ret.begin(),ret.end());
    20. return ret;
    21. }

    Moris中序:(左,中,右)

    1. vector<int> inMoris(TreeNode* root){
    2. vector<int> ret;
    3. if(root==nullptr){
    4. return ret;
    5. }
    6. stack<TreeNode*> stk;
    7. TreeNode* cur=root;
    8. while(stk.empty()==false||cur!=nullptr){
    9. if(cur!=nullptr){
    10. stk.push(cur);
    11. cur=cur->left;
    12. }else{
    13. TreeNode* tmp=stk.top();
    14. stk.pop();
    15. ret.emplace_back(tmp->val);
    16. cur=tmp->right;
    17. }
    18. }
    19. return ret;
    20. }