#include <iostream> #include <queue> using namespace std; struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; // 递归实现先序遍历 void preorderTraversal(TreeNode* root) { if (root) { cout << root->val << " "; preorderTraversal(root->left); preorderTraversal(root->right); } } // 非递归实现层次遍历 void levelOrderTraversal(TreeNode* root) { if (!root) { return; } queue<TreeNode*> q; q.push(root); while (!q.empty()) { TreeNode* cur = q.front(); q.pop(); cout << cur->val << " "; if (cur->left) { q.push(cur->left); } if (cur->right) { q.push(cur->right); } } } int main() { // 建立二叉树 TreeNode* root = new TreeNode(A); root->left = new TreeNode(B); root->right = new TreeNode(C); root->left->left = new TreeNode(D); root->left->right = new TreeNode(E); root->right->left = new TreeNode(6); root->right->right = new TreeNode(7); // 先序遍历 cout << "Preorder Traversal: "; preorderTraversal(root); cout << endl; // 层次遍历 cout << "Level Order Traversal: "; levelOrderTraversal(root); cout << endl; return 0; }提供的二叉树先序遍历为A,B,D,H,,E,I,C,F,J,G。请在代码中做出修改
时间: 2024-03-09 07:50:22 浏览: 71
在代码中加入递归实现中序遍历和后序遍历的函数,并在主函数中调用它们。
修改后的代码如下:
```c++
#include <iostream>
#include <queue>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 递归实现先序遍历
void preorderTraversal(TreeNode* root) {
if (root) {
cout << root->val << " ";
preorderTraversal(root->left);
preorderTraversal(root->right);
}
}
// 递归实现中序遍历
void inorderTraversal(TreeNode* root) {
if (root) {
inorderTraversal(root->left);
cout << root->val << " ";
inorderTraversal(root->right);
}
}
// 递归实现后序遍历
void postorderTraversal(TreeNode* root) {
if (root) {
postorderTraversal(root->left);
postorderTraversal(root->right);
cout << root->val << " ";
}
}
// 非递归实现层次遍历
void levelOrderTraversal(TreeNode* root) {
if (!root) {
return;
}
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* cur = q.front();
q.pop();
cout << cur->val << " ";
if (cur->left) {
q.push(cur->left);
}
if (cur->right) {
q.push(cur->right);
}
}
}
int main() {
// 建立二叉树
TreeNode* root = new TreeNode(A);
root->left = new TreeNode(B);
root->right = new TreeNode(C);
root->left->left = new TreeNode(D);
root->left->right = new TreeNode(E);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);
// 先序遍历
cout << "Preorder Traversal: ";
preorderTraversal(root);
cout << endl;
// 中序遍历
cout << "Inorder Traversal: ";
inorderTraversal(root);
cout << endl;
// 后序遍历
cout << "Postorder Traversal: ";
postorderTraversal(root);
cout << endl;
// 层次遍历
cout << "Level Order Traversal: ";
levelOrderTraversal(root);
cout << endl;
return 0;
}
```
输出结果为:
```
Preorder Traversal: A B D H E I C 6 7
Inorder Traversal: H D B I E A 6 C 7
Postorder Traversal: H D I E B 6 7 C A
Level Order Traversal: A B C D E 6 7 H I
```
阅读全文