145.二叉树的后序遍历
- 题目描述
给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历 。
145.二叉树的后续遍历
- 递归
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> vec;
postorder(root,vec);
return vec;
}
void postorder(TreeNode* root , vector<int>& v){
if(root == nullptr)
return ;
postorder(root->left , v);
postorder(root->right , v);
v.push_back(root->val);
}
};
- 迭代(非递归)
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> vec;
if(!root)
return vec;
TreeNode * q = root;
TreeNode * lastvist = nullptr;
while(q != nullptr || !st.empty()){
while(q != nullptr){
st.push(q);
q = q -> left;
}
if(!st.empty()){
q = st.top();
if(q->right != nullptr && q->right != lastvist){//右子树存在且没被访问过
q = q -> right;
st.push(q);//让右孩子入栈
q = q -> left;
}
else{//右子树为空或被访问过
//此时可以打印根结点了
vec.push_back(q->val);
lastvist = q;
st.pop();
q = nullptr;
}
}
}
return vec;
}
};
这篇博客介绍了如何使用递归和迭代两种方法实现二叉树的后序遍历。递归方法直接通过调用自身来遍历左子树、右子树和根节点。迭代方法利用栈来模拟递归过程,首先遍历左子树,然后检查右子树,最后处理根节点。这两种方法都有效地解决了二叉树后序遍历的问题。
665

被折叠的 条评论
为什么被折叠?



