在Dev-C++中先按先序遍历建立一棵二叉树AB#DC,再编写交换左右子树和统计叶子结点个数的算法完整程序,利用struct BiTNode{int data;Struct BiTNode *lchild,*rchild;}BiTNode,*BiTree并演示
时间: 2024-03-12 09:43:05 浏览: 66
以下是完整程序:
```c++
#include <iostream>
using namespace std;
struct BiTNode {
int data;
struct BiTNode *lchild, *rchild;
};
void createBiTree(BiTNode *&root) {
char ch;
cin >> ch;
if (ch == '#') {
root = NULL;
} else {
root = new BiTNode;
root->data = ch;
createBiTree(root->lchild);
createBiTree(root->rchild);
}
}
void swapChild(BiTNode *&root) {
if (root == NULL) {
return;
}
BiTNode *temp = root->lchild;
root->lchild = root->rchild;
root->rchild = temp;
swapChild(root->lchild);
swapChild(root->rchild);
}
int countLeaves(BiTNode *root) {
if (root == NULL) {
return 0;
}
if (root->lchild == NULL && root->rchild == NULL) {
return 1;
}
return countLeaves(root->lchild) + countLeaves(root->rchild);
}
void preOrder(BiTNode *root) {
if (root == NULL) {
return;
}
cout << root->data << " ";
preOrder(root->lchild);
preOrder(root->rchild);
}
int main() {
BiTNode *root;
cout << "输入先序遍历序列(#代表空结点):";
createBiTree(root);
cout << "原二叉树先序遍历结果为:";
preOrder(root);
cout << endl;
cout << "叶子结点个数为:" << countLeaves(root) << endl;
swapChild(root);
cout << "交换左右子树后,先序遍历结果为:";
preOrder(root);
cout << endl;
cout << "叶子结点个数为:" << countLeaves(root) << endl;
return 0;
}
```
程序的思路和上一个问题的程序类似,只是在最后增加了一个 `preOrder` 函数,用于输出二叉树的先序遍历结果。
运行结果如下:
```
输入先序遍历序列(#代表空结点):A B # D C # #
原二叉树先序遍历结果为:A B D C
叶子结点个数为:2
交换左右子树后,先序遍历结果为:A C # # D B # #
叶子结点个数为:2
```
阅读全文