c++二叉树文件读取
时间: 2023-12-02 11:41:29 浏览: 93
以下是C++中读取二叉树文件的示例代码:
```c++
#include <iostream>
#include <fstream>
using namespace std;
struct TreeNode {
char val;
TreeNode* left;
TreeNode* right;
TreeNode(char x) : val(x), left(NULL), right(NULL) {}
};
void buildTree(TreeNode*& root, ifstream& fin) {
char ch;
if (!fin.eof()) {
fin >> ch;
if (ch == '0') {
root = NULL;
} else {
root = new TreeNode(ch);
buildTree(root->left, fin);
buildTree(root->right, fin);
}
}
}
void preOrder(TreeNode* root) {
if (root) {
cout << root->val << " ";
preOrder(root->left);
preOrder(root->right);
}
}
void inOrder(TreeNode* root) {
if (root) {
inOrder(root->left);
cout << root->val << " ";
inOrder(root->right);
}
}
void postOrder(TreeNode* root) {
if (root) {
postOrder(root->left);
postOrder(root->right);
cout << root->val << " ";
}
}
int main() {
ifstream fin("tree.txt");
TreeNode* root;
buildTree(root, fin);
cout << "Preorder traversal: ";
preOrder(root);
cout << endl;
cout << "Inorder traversal: ";
inOrder(root);
cout << endl;
cout << "Postorder traversal: ";
postOrder(root);
cout << endl;
fin.close();
return 0;
}
```
阅读全文
相关推荐
















