0145.cpp (760B)
1 class Solution { 2 public: 3 vector<int> postorderTraversal(TreeNode *root) { 4 if (!root) return {}; 5 6 vector<int> res; 7 unordered_set<TreeNode *> s; 8 stack<TreeNode *> st; 9 10 while (root) { 11 st.push(root); 12 root = root->left; 13 } 14 15 while (!st.empty()) { 16 TreeNode *root = st.top(); 17 st.pop(); 18 if (!s.count(root)) { 19 s.insert(root); 20 st.push(root); 21 root = root->right; 22 while (root) { 23 st.push(root); 24 root = root->left; 25 } 26 } else { 27 res.push_back(root->val); 28 } 29 } 30 31 return res; 32 } 33 };