Given a binary tree, return the postorder traversal of its nodes' values.
Example:
Input:[1,null,2,3]
1 \ 2 / 3 Output:[3,2,1]
Follow up: Recursive solution is trivial, could you do it iteratively?
preorder是 root-left-right postorder是 left-right-root 那我们在preorder的基础上,改动push进stack的顺序,使得root-right-left 再翻转一下,也就是后pop出来的放进res vector的最前面,就实现left-right-root了 实现:class Solution { public: vector<int> postorderTraversal(TreeNode* root) { vector<int> res; if (!root) return res; stack<TreeNode*> st; st.push(root); while(!st.empty()){ TreeNode* cur = st.top(); st.pop(); res.insert(res.begin(), cur->val); if (cur->left) st.push(cur->left); if (cur->right) st.push(cur->right); } return res; } };