给定一棵二叉树,使用非递归的方式实现二叉树左右子树交换,并输出后序遍历结果,要求补全以下代码空白#include "binary_tree.h" … /********** Begin / /* End **********/ }
时间: 2023-09-26 08:04:47 浏览: 100
#include <stack>
#include "binary_tree.h"
void postorderTraversal(TreeNode* root) {
if (root == nullptr) {
return;
}
std::stack<TreeNode*> s;
s.push(root);
while (!s.empty()) {
TreeNode* node = s.top();
s.pop();
if (node->left != nullptr) {
s.push(node->left);
}
if (node->right != nullptr) {
s.push(node->right);
}
// 交换左右子树
TreeNode* temp = node->left;
node->left = node->right;
node->right = temp;
}
// 后序遍历
std::stack<TreeNode*> output;
output.push(root);
while (!output.empty()) {
TreeNode* node = output.top();
output.pop();
if (node->left != nullptr) {
output.push(node->left);
}
if (node->right != nullptr) {
output.push(node->right);
}
std::cout << node->val << " ";
}
}
阅读全文