答案是:C++中二叉树后序遍历有递归和迭代两种方法,顺序为左→右→根,递归简洁但可能栈溢出,迭代用栈模拟,适合深树。

在C++中实现二叉树的后序遍历,主要有两种方法:递归和迭代。后序遍历的顺序是“左子树 → 右子树 → 根节点”,适合用于释放树节点或计算表达式树等场景。
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
<pre class="brush:php;toolbar:false;">
void postorderTraversalRecursive(TreeNode* root) {
if (root == nullptr) return;
<pre class="brush:php;toolbar:false;"><code>postorderTraversalRecursive(root->left); // 遍历左子树
postorderTraversalRecursive(root->right); // 遍历右子树
std::cout << root->val << " "; // 访问根节点}
优点是代码简洁易懂,缺点是在树很深时可能引发栈溢出。一种常见做法是使用一个指针记录上一个访问的节点,避免重复进入右子树:
void postorderTraversalIterative(TreeNode* root) {
if (root == nullptr) return;
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">std::stack<TreeNode*> stack;
TreeNode* lastVisited = nullptr;
TreeNode* current = root;
while (current != nullptr || !stack.empty()) {
if (current != nullptr) {
stack.push(current);
current = current->left; // 一直向左走
} else {
TreeNode* peekNode = stack.top();
// 如果右子树存在且未被访问过,进入右子树
if (peekNode->right != nullptr && lastVisited != peekNode->right) {
current = peekNode->right;
} else {
std::cout << peekNode->val << " ";
lastVisited = stack.top();
stack.pop();
}
}
}}
这种方法空间复杂度为O(h),h为树的高度,适合深度较大的树。你可以这样测试上述代码:
int main() {
TreeNode* root = new TreeNode(1);
root->right = new TreeNode(2);
root->right->left = new TreeNode(3);
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">std::cout << "后序遍历结果: ";
postorderTraversalRecursive(root); // 输出: 3 2 1
std::cout << std::endl;
return 0;}
基本上就这些。递归写起来快,迭代更安全。根据实际需求选择合适的方法即可。
立即学习“C++免费学习笔记(深入)”;
以上就是c++++中如何实现后序遍历_c++二叉树后序遍历方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号