二叉树的创建与遍历代码
时间: 2023-11-25 08:04:46 浏览: 75
二叉树代码遍历和创建等
以下是二叉树的创建与遍历代码:
1. 二叉树的创建
```c++
typedef struct BiNode {
char data;
struct BiNode *left, *right;
} BiNode, *BiTree;
void CreateBiTree(BiTree &T) {
char key;
cout << "请先序输入字符:";
cin >> key;
if (key == '#') {
T = NULL;
} else {
T = (BiNode*) malloc(sizeof(BiNode));
T->data = key;
CreateBiTree(T->left);
CreateBiTree(T->right);
}
}
```
2. 二叉树的遍历
(1)先序遍历(DLR)
```c++
void PreOrder(BiTree T) {
if (T) {
cout << T->data << " ";
PreOrder(T->left);
PreOrder(T->right);
}
}
```
(2)中序遍历(LDR)
```c++
void InOrder(BiTree T) {
if (T) {
InOrder(T->left);
cout << T->data << " ";
InOrder(T->right);
}
}
```
(3)后序遍历(LRD)
```c++
void PostOrder(BiTree T) {
if (T) {
PostOrder(T->left);
PostOrder(T->right);
cout << T->data << " ";
}
}
```
阅读全文