1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| vector<int> postorderTraversal(TreeNode* root) { vector<int> res; stack<TreeNode*> st; TreeNode* cur = root; TreeNode* prenode; while(cur != nullptr || !st.empty()){ if(cur != nullptr){ st.push(cur); cur = cur->left; }else{ cur = st.top(); st.pop(); if(cur->right == nullptr || cur->right == prenode){ res.push_back(cur->val); prenode = cur; cur = nullptr; }else{ st.push(cur); cur = cur->right; } } } return res; }
vector<int> REVERpreorderTraversal(TreeNode* root) { stack<TreeNode*> st; vector<int> res; TreeNode* cur = root; while(cur != nullptr || !st.empty()){ if(cur != nullptr){ res.push_back(cur->val); st.push(cur); cur = cur->right; }else{ cur = st.top(); st.pop(); cur = cur->left; } } reverse(res.begin(), res.end()); return res; }
class Solution { public: std::vector<int> postorderTraversal(TreeNode* root) { std::vector<int> res; if (!root) return res; std::stack<TreeNode*> st1; std::stack<TreeNode*> st2; st1.push(root); while (!st1.empty()) { TreeNode* node = st1.top(); st1.pop(); st2.push(node); if (node->left) st1.push(node->left); if (node->right) st1.push(node->right); } while (!st2.empty()) { res.push_back(st2.top()->val); st2.pop(); } return res; } };
|