#include<stdio.h>
#include<stdlib.h>
#include <iostream>
using namespace std;
typedef struct TreeNode
{
struct TreeNode* lchild, * rchild;
char data;
}RTreeNode;
//生成二叉树
RTreeNode* CreateTree()
{
char data;
char temp;
RTreeNode* root;
cin >> data; // 输入数据
temp = cin.get(); // 清除缓冲区‘\n’
if (data == '/') { // 输入‘/’ 代表此节点下子树为空,不执行递归
return NULL;
}
else {
root = (struct TreeNode*)malloc(sizeof(struct TreeNode)); // 分配内存空间
if (root == NULL)
cout << "Memory allocation failed!" << endl;
else root->data = data; // 把当前输入的数据存入当前节点指针的数据域中
cout << "Please input left node of " << data << endl;
root->lchild = CreateTree(); // 开始递归创建左子树
cout << "Please input right node of " << data << endl;
root->rchild = CreateTree(); // 开始到上一级节点的右边递归创建左右子树
return root;
}
}
//求叶子节点函数
int LeafNode(RTreeNode* p)
{
if (!p)
{
return 0; //空二叉树的情况
}
else if (p->lchild == NULL && p->rchild == NULL)//没有左右子节点的节点为叶子节点
{
return +1;
}
else
{
return LeafNode(p->lchild) + LeafNode(p->rchild);
}
} //因为我们用的递归是根节点开始的,所以必须把递归的函数放在else(非叶子节点这里)
//求双亲节点函数
int ParentNode(RTreeNode* p)
{
if (!p)
{
return 0; //空二叉树
}
else if (p->lchild == NULL && p->rchild == NULL)
{
return 0; //节点为叶子节点 = 左子树 + 右子树 = NULL
}
else
{
return ParentNode(p->lchild) + ParentNode(p->rchild) + 1;
}
}
//打印双亲节点
void ParentNodeShow(RTreeNode* p)
{
if (p == NULL)
{
return;
}
if (!(p->lchild == NULL && p->rchild == NULL)) //为叶子节点的
{
cout << p->data << " ";
}
ParentNodeShow(p->lchild);
ParentNodeShow(p->rchild);
}
//打印叶子节点
void LeafNodeShow(RTreeNode* p)
{
if (p == NULL)
{
return;
}
if (p->lchild == NULL && p->rchild == NULL)
{
cout << p->data << " ";
}
LeafNodeShow(p->lchild);
LeafNodeShow(p->rchild);
}
//先序遍历 DLR
void Preorder(RTreeNode* p)
{
if (p == NULL)
{
return;
}
cout << p->data << " ";
Preorder(p->lchild);
Preorder(p->rchild);
}
//中序遍历 LDR
void Inorder(RTreeNode* p)
{
if (p == NULL)
{
return;
}
Preorder(p->lchild);
cout << p->data << " ";
Preorder(p->rchild);
}
//后序遍历 LRD
void Postorder(RTreeNode* p)
{
if (p == NULL)
{
return;
}
Preorder(p->lchild);
Preorder(p->rchild);
cout << p->data << " ";
}
int main()
{
RTreeNode* root;
cout << "Please input root node : " << endl;
root = CreateTree();
cout << "Preorder :" << endl;
Preorder(root);
cout << endl;
cout << "Inorder :" << endl;
Inorder(root);
cout << endl;
cout << "Postorder :" << endl;
Postorder(root);
cout << endl;
cout << "There are " << ParentNode(root) << " parents" << endl;
cout << "Show Parents:" << endl;
ParentNodeShow(root);
cout << endl;
cout << "There are " << LeafNode(root) << " children" << endl;
cout << "Show Children:" << endl;
LeafNodeShow(root);
return 0;
}
从键盘输入创建二叉树、先序遍历、中序遍历、后序遍历、统计子节点和叶子节点的个数。
最新推荐文章于 2023-06-29 10:59:49 发布