# 145

Mar 25th, 2021
63
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. /**
2.  * Definition for a binary tree node.
3.  * struct TreeNode {
4.  *     int val;
5.  *     TreeNode *left;
6.  *     TreeNode *right;
7.  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
8.  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9.  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10.  * };
11.  */
12. class Solution {
13. public:
14.     vector<int> postorderTraversal(TreeNode* root) {
15.         vector<int> ans;
16.         stack<TreeNode*> s;
17.
18.         if(root) s.push(root);
19.         while(!s.empty()){
20.             TreeNode *tmp = s.top();
21.             s.pop();
22.             ans.push_back(tmp->val);
23.             if(tmp->left) s.push(tmp->left);
24.             if(tmp->right) s.push(tmp->right);
25.         }
26.         reverse(ans.begin(), ans.end());
27.         return ans;
28.     }
29. };
RAW Paste Data