要求:
1.采用双链表作为存贮结构,完成二叉树的建立;
2.给出先序、中序、和后序遍历算法;
3.给出求二叉树所有结点个数、叶子结点个数及树高度的算法
代码实现:
typedef struct BTreeNode {
int data;
BTreeNode *Lchild, *Rchild;
}Bnode, *ptr;
class BTree
{
public:
ptr getRoot()
{ return root; }
void Create() //构造二叉树的对外接口
{ root = createBTree(); }
void inOrder(ptr); //中序遍历
void preOrder(ptr); //先序遍历
void postOrder(ptr); //后序遍历
int BTreeSize(ptr); //结点个数
int BTreeLeaves(ptr); //叶子结点
int BTreeHeight(ptr); //树高
private:
ptr root;
ptr createBTree(); //根据扩充序列构建二叉树
};
ptr BTree::createBTree() {
ptr p;
int x;
cin >> x;
if (x == 0)
return NULL;
p = new Bnode;
p->data = x;
p->Lchild = createBTree();
p->Rchild = createBTree();
return p;
}
void BTree::preOrder(ptr p) {//先序遍历
cout << p->data << " ";
if (p->Lchild != NULL)
preOrder(p->Lchild);
if (p->Rchild != NULL)
preOrder(p->Rchild);
}
void BTree::inOrder(ptr p) {//中序遍历
if (p->Lchild != NULL)
inOrder(p->Lchild);
cout << p->data << " ";
if (p->Rchild != NULL)
inOrder(p->Rchild);
}
void BTree::postOrder(ptr p) {//后序遍历
if (p->Lchild != NULL)
postOrder(p->Lchild);
if (p->Rchild != NULL)
postOrder(p->Rchild);
cout << p->data << " ";
}
int BTree::BTreeSize(ptr p) {//结点个数
if (p == NULL)
return 0;
else
return 1 + BTreeSize(p->Lchild) + BTreeSize(p->Rchild);
}
int BTree::BTreeLeaves(ptr p) {//叶子结点
if (p == NULL)
return 0;
else
if (p->Lchild == NULL && p->Rchild == NULL)
return 1;
else
return BTreeLeaves(p->Lchild) + BTreeLeaves(p->Rchild);
}
int BTree::BTreeHeight(ptr p) {//树高
if (p != NULL) {
return max(BTreeHeight(p->Lchild), BTreeHeight(p->Rchild)) + 1;
}
else {
return 0;
}
}
void menu() {
cout << "==== ====" << endl;
cout << "1.先序遍历" << endl;
cout << "2.中序遍历" << endl;
cout << "3.后序遍历" << endl;
cout << "4.求结点个数" << endl;
cout << "5.求叶子结点个数" << endl;
cout << "6.求树的高度" << endl;
cout << "==== ====" << endl;
}
//主函数
void main()
{
cout << "请输入一个扩充序列: " << endl;
BTree tree = BTree();
tree.Create();
cout << "二叉树构建完成!" << endl;
int x;
int y;
menu();
do {
cout << "请输入操作代码:";
cin >> x;
switch (x) {
case 1:
tree.preOrder(tree.getRoot());
cout << endl;
break;
case 2:
tree.inOrder(tree.getRoot());
cout << endl;
break;
case 3:
tree.postOrder(tree.getRoot());
cout << endl;
break;
case 4:
y=tree.BTreeSize(tree.getRoot());
cout << "树共有" << y << "个结点";
cout << endl;
break;
case 5:
y=tree.BTreeLeaves(tree.getRoot());
cout << "树共有" << y << "个叶子";
cout << endl;
break;
case 6:
y=tree.BTreeHeight(tree.getRoot());
cout << "树高为:" << y ;
cout << endl;
break;
default:
cout << "无该选项!" << endl;
}
} while (x<7);
}
注意最后运行时的输出,假如是输入1,2,3,后面没有数据的话,必须补上0,0,0,0;才是一个完整的树结构,如: