给定一个二叉树,返回它的 后序 遍历。

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

递归:

class Solution {
public:
vector<int> res;
vector<int> postorderTraversal(TreeNode* root) {
if(root == NULL)
return res;
postorderTraversal(root ->left);
postorderTraversal(root ->right);
res.push_back(root ->val);
return res;
}
};

迭代:

方法一:

class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> s;
s.push(root);
vector<int> res;
if(root == NULL)
return res;
while(!s.empty())
{
TreeNode* temp = s.top();
if(temp->left)
{
s.push(temp->left);
temp->left = NULL;
}
else if(temp->right)
{
s.push(temp->right);
temp->right = NULL;
}
else
{
res.push_back(temp->val);
s.pop();
}
}
return res;
}
};

方法二:

class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
if(root == NULL)
return res;
stack<TreeNode *> s;
s.push(root);
while(!s.empty())
{
TreeNode* node = s.top();
s.pop();
res.push_back(node ->val);
if(node ->left)
s.push(node ->left);
if(node ->right)
s.push(node ->right);
} return vector<int>(res.rbegin(), res.rend());
}
};
05-08 08:45