算法描述:
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?
解题思路:用栈模拟。
vector<int> postorderTraversal(TreeNode* root) { vector<int> results; if(root==nullptr) return results; stack<TreeNode*> stk; stk.push(root); while(!stk.empty()){ TreeNode* temp = stk.top(); stk.pop(); results.insert(results.begin(),temp->val); if(temp->left) stk.push(temp->left); if(temp->right) stk.push(temp->right); } return results; }