给定一棵二叉树,使用非递归的方式实现二叉树左右子树交换,并输出后序遍历结果。要求完善以下代码#include "binary_tree.h" … /********** Begin / /* End **********/ }
时间: 2023-09-04 17:08:14 浏览: 94
下面是完整代码实现:
```
#include "binary_tree.h"
#include <stack>
#include <iostream>
using namespace std;
void swapTree(TreeNode* root) {
if (root == nullptr) return;
stack<TreeNode*> s;
s.push(root);
while (!s.empty()) {
TreeNode* node = s.top();
s.pop();
swap(node->left, node->right);
if (node->left) s.push(node->left);
if (node->right) s.push(node->right);
}
}
void postOrder(TreeNode* root) {
if (root == nullptr) return;
stack<TreeNode*> s1, s2;
s1.push(root);
while (!s1.empty()) {
TreeNode* node = s1.top();
s1.pop();
s2.push(node);
if (node->left) s1.push(node->left);
if (node->right) s1.push(node->right);
}
while (!s2.empty()) {
TreeNode* node = s2.top();
s2.pop();
cout << node->val << " ";
}
}
int main() {
TreeNode* root = createTreeNode(1);
root->left = createTreeNode(2);
root->right = createTreeNode(3);
root->left->left = createTreeNode(4);
root->left->right = createTreeNode(5);
root->right->left = createTreeNode(6);
root->right->right = createTreeNode(7);
swapTree(root);
postOrder(root);
return 0;
}
```
其中 `swapTree` 函数用于交换二叉树的左右子树,采用非递归方式实现。 `postOrder` 函数用于输出交换后的二叉树的后序遍历结果,也采用非递归方式实现。在 `main` 函数中,我们首先创建一棵二叉树,然后调用 `swapTree` 函数交换左右子树,最后调用 `postOrder` 函数输出后序遍历结果。
阅读全文