code:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
void behindtraversal(vector<int>&result,TreeNode*root)
{
if(root==NULL)return;
behindtraversal(result,root->left);
behindtraversal(result,root->right);
result.push_back(root->val);
return;
}
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
behindtraversal(result,root);
return result;
}
};
迭代法:
code:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int>result;
if(root==NULL)return result;
stack<TreeNode*>st;
st.push(root);
while(!st.empty())
{
TreeNode*cur=st.top();
st.pop();
result.push_back(cur->val);
if(cur->left)st.push(cur->left);
if(cur->right)st.push(cur->right);
}
reverse(result.begin(),result.end());
return result;
}
};