要求:迭代
思路:先序遍历是中左右,后续遍历是左右中,那么我们只需要调整一下先序遍历的代码顺序,就变成中右左的遍历顺序,然后在反转vector数组,输出的结果顺序就是左右中了
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
if(!root)return {};
vector<int> v;
stack<TreeNode*> s;
s.push(root);
while(!s.empty()){
TreeNode* tmp=s.top();
s.pop();
v.push_back(tmp->val);
if(tmp->left)s.push(tmp->left);
if(tmp->right)s.push(tmp->right);
}
reverse(v.begin(),v.end());
return v;
}
};