递归:
vector<int> postorderTraversal(TreeNode *root) {
vector<int> result;
if(root==NULL)
return result;
PostCore(root,result);
return result;
}
void PostCore(TreeNode* root,vector<int>& result){
if(root->left){
PostCore(root->left,result);
}
if(root->right)
PostCore(root->right,result);
result.push_back(root->val);
}
非递归:
vector<int> postorderTraversal(TreeNode *root) {
vector<int> result;
if(root==NULL)
return result;
stack<TreeNode*> trees;
trees.push(root);
while(!trees.empty()){
TreeNode* pNode=trees.top();
if(pNode->left==NULL&&pNode->right==NULL){
result.push_back(pNode->val);
trees.pop();
}
if(pNode->right){
trees.push(pNode->right);
pNode->right=NULL;
}
if(pNode->left){
trees.push(pNode->left);
pNode->left=NULL;
}
}
return result;
}
利用前序遍历:把根-》左-》右 变为 根-》右-》左 再把 结果 reverse
利用 栈
vector<int> postorderTraversal(TreeNode *root) {
vector<int> result;
if(root==NULL)
return result;
stack<TreeNode*> trees;
trees.push(root);
while(!trees.empty()){
TreeNode* pNode=trees.top();
trees.pop();
result.push_back(pNode->val);
if(pNode->left)
trees.push(pNode->left);
if(pNode->right)
trees.push(pNode->right);
}
reverse(result.begin(),result.end());
return result;
}