Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
后续遍历,“先左再右后中”,翻转过来就是“先中再右后左”,我们把根节点root存入一个stack里面,并通过这个stack遍历二叉树。stack头节点出栈并存到vector里,然后把当前节点的左孩子、右孩子先后入栈,对stack头节点进行循环操作,直到stack为空。这是的vector存储的是“先中再右后左”的顺序,reverse一次,变为postorder.
class Solution { public: vector<int> postorderTraversal(TreeNode *root) { vector<int> res; if(root==NULL)return res; stack<TreeNode*> st; st.push(root); while(!st.empty()){ TreeNode* temp = st.top();st.pop(); res.push_back(temp->val); if(temp->left)st.push(temp->left); if(temp->right)st.push(temp->right); } reverse(res.begin(),res.end()); return res; } };