Given a binary tree, return the postorder traversal of its nodes’ values.
给定一个二叉树,返回后序遍历的节点值。
For example:
Given binary tree{1,#,2,3},
//递归实现
class Solution {
public:
void recursive (TreeNode* root, vector<int>& ivec) {
if(root) {
recursive(root->left,ivec);
recursive(root->right,ivec);
ivec.push_back(root->val);
}
}
vector<int> postorderTraversal(TreeNode *root) {
vector<int> ivec;
recursive(root,ivec);
return ivec;
}
};
Note: Recursive solution is trivial, could you do it iteratively?
注意:递归是低效的,你能用迭代实现吗?
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root){
vector<int>ivec;
if(!root) {
return ivec;
}
stack<TreeNode* >stactTree;
stactTree.push(root);
TreeNode* cur;
while(!stactTree.empty()){
cur = stactTree.top();
if(cur->left == NULL && cur->right == NULL){
ivec.push_back(cur->val);
stactTree.pop();
}
else{
if(cur->right != NULL){
stactTree.push(cur->right);
cur->right = NULL;
}
if(cur->left != NULL){
stactTree.push(cur->left);
cur->left = NULL;
}
}
}
return ivec;
}
};