给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/binary-tree-postorder-traversal 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> ans;
preorder(root, ans);
return ans;
}
void preorder(TreeNode* root, vector<int> &ans)
{
if(root == NULL)
return;
preorder(root->left, ans);
preorder(root->right, ans);
ans.push_back(root->val);
}
};
左右根
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> ans;
stack<TreeNode*> stk;
while(root || !stk.empty())
{
while(root)
{
stk.push(root);
ans.push_back(root->val);
root = root->right;
}
root = stk.top()->left;
stk.pop();
}
//反转遍历结果
reverse(ans.begin(),ans.end());
return ans;
}
};
以下解法会破坏二叉树
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> ans;
if(root==NULL)
return ans;
TreeNode *cur;
stack<TreeNode*> stk;
stk.push(root);
while(!stk.empty())
{
cur = stk.top();
if(cur->left)
{
stk.push(cur->left);
cur->left = NULL;
}
else if(cur->right)
{
stk.push(cur->right);
cur->right = NULL;
}
else
{
ans.push_back(cur->val);
stk.pop();
}
}
return ans;
}
};
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
vector<int> ans;
if(root == NULL) return ans;
stack<TreeNode*> stk1;
stack<TreeNode*> stk2;
stk1.push(root);
TreeNode *cur;
while(!stk1.empty())
{
cur = stk1.top();
stk1.pop();
stk2.push(cur);
if(cur->left)
stk1.push(cur->left);
if(cur->right)
stk1.push(cur->right);
}
while(!stk2.empty())
{
cur = stk2.top();
stk2.pop();
ans.push_back(cur->val);
}
return ans;
}
};