#include <iostream> #include <queue> #include<string> 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(65); root->left = new TreeNode(66); root->right = new TreeNode(67); root->left->left = new TreeNode(68); root->left->right = new TreeNode(69); root->left->left->left = new TreeNode(72); root->left->right->right = new TreeNode(73); root->right->left = new TreeNode(70); root->right->right = new TreeNode(71); root->right->left->left = new TreeNode(74); // 先序遍历 cout << "Preorder Traversal: "; preorderTraversal(root); cout << endl; // 层次遍历 cout << "Level Order Traversal: "; levelOrderTraversal(root); cout << endl; return 0; }怎么将代码内节点的数字改成字母
时间: 2024-03-09 12:51:43 浏览: 77
使用include <iostream>时一定要加using namespace std
要将节点的数字改成字母,可以将 TreeNode 结构体中的 val 成员变量改为 string 类型,并将节点的值赋为相应的字母。例如,将节点的数字 65 改为字母 A,将节点的数字 66 改为字母 B,以此类推,可以将代码修改如下:
```
#include <iostream>
#include <queue>
#include <string>
using namespace std;
struct TreeNode {
string val; // 将节点的值从 int 类型改为 string 类型
TreeNode* left;
TreeNode* right;
TreeNode(string s) : val(s), 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->left->left->left = new TreeNode("H");
root->left->right->right = new TreeNode("I");
root->right->left = new TreeNode("F");
root->right->right = new TreeNode("G");
root->right->left->left = new TreeNode("J");
// 先序遍历
cout << "Preorder Traversal: ";
preorderTraversal(root);
cout << endl;
// 层次遍历
cout << "Level Order Traversal: ";
levelOrderTraversal(root);
cout << endl;
return 0;
}
```
这样就可以将节点的数字改成相应的字母了。
阅读全文