Given a binary tree, return thepostorder 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?
方法一:
(1)前序遍历:根-》左-》右
(2)变成:根-》右-》左
(3)然后逆序
class Solution
{
public:
vector<int> postorderTraversal(TreeNode* root)
{
vector<int> res;
if (!root)
{
return res;
}
stack<TreeNode*> st;
st.push(root);
while (st.size())
{
TreeNode* tmp = st.top();
st.pop();
res.push_back(tmp->val);
if (tmp->left)
{
st.push(tmp->left);
}
if (tmp->right)
{
st.push(tmp->right);
}
}
reverse(res.begin(), res.end());
}
};
方法二:递归实现
class Solution
{
public:
vector<int> postorderTraversal(TreeNode* root)
{
vector<int> ans;
LRD(ans, root);
return ans;
}
void LRD(vector<int>&ans, TreeNode* root)
{
if (root==NULL)
{
return;
}
LRD(ans, root->left);
LRD(ans, root->right);
ans.push_back(root->val);
}
};