68-Binary Tree Postorder Traversal
阅读原文时间:2023年07月09日阅读:2
  1. Binary Tree Postorder Traversal My Submissions QuestionEditorial Solution

    Total Accepted: 97358 Total Submissions: 273744 Difficulty: Hard

    Given a binary tree, return the postorder traversal of its nodes’ values.

For example:

Given binary tree {1,#,2,3},

1

\

2

/

3

return [3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?

二叉树的后续遍历,不使用递归实现

思路:类似于中序,需要额外使用一个map来保存相应的访问转态

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        if(root==NULL)return res;
        stack<TreeNode*> st;
        st.push(root);
        TreeNode * rn=root;
        map<TreeNode*,int> map;
        map[rn]=1;
        while(!st.empty()){
            while(rn!=NULL&&rn->left!=NULL&&!map.count(rn->left)){//走到最左下角
                st.push(rn->left);
                rn = rn->left;
                map[rn]=1;
            }
            if(rn->right!=NULL&&!map.count(rn->right)){ //右子树不空进入右子树
                rn = rn->right;
                st.push(rn);
                map[rn]=1;
            }
            else {                                     //为空则访问该节点
                res.push_back(rn->val);
                st.pop();
                if(!st.empty())rn = st.top();           //回溯到上一个节点
            }
        }
        return res;
    }
};