#include<iostream>
using namespace std;
typedef struct BinaryTree
{
int data;
struct BinaryTree *Left;
struct BinaryTree *Right;
}Node;
Node* createBinaryTree()
{
Node *p = NULL;
int c;
while (cin >> c)
{
if (c == 0) //叶子节点的左、右子树分别赋值为0
{
p = NULL;
}
else
{
p = (Node*)malloc(sizeof(Node));
p->data = c;
p->Left = createBinaryTree(); //递归创建左子树
p->Right = createBinaryTree(); //递归创建右子树
}
}
return p;
}
//先序遍历
void PreOrderTraverse(Node* BinaryRoot)
{
if (BinaryRoot == NULL)
{
return;
}
cout << BinaryRoot->data << ' ';
if(BinaryRoot->Left!=NULL)
PreOrderTraverse(BinaryRoot->Left);
if(BinaryRoot->Right!=NULL)
PreOrderTraverse(BinaryRoot->Right);
}
//中序遍历
void InOrderTraverse(Node* BinaryRoot)
{
if (BinaryRoot == NULL)
{
return;
}
if(BinaryRoot->Left!=NULL)
InOrderTraverse(BinaryRoot->Left);
cout << BinaryRoot->data << ' ';
if(BinaryRoot->Right!=NULL)
InOrderTraverse(BinaryRoot->Right);
}
//后序遍历
void LastOrderTraverse(Node* BinaryRoot)
{
if (BinaryRoot == NULL)
return;
if(BinaryRoot->Left!=NULL)
LastOrderTraverse(BinaryRoot->Left);
if(BinaryRoot->Right!=NULL)
LastOrderTraverse(BinaryRoot->Right);
cout << BinaryRoot->data << ' ';
}
//二叉树节点总数目
int NodeNum(Node* BinaryRoot)
{
if (BinaryRoot == NULL)
{
return 0;
}
else
{
return 1 + NodeNum(BinaryRoot->Left) + NodeNum(BinaryRoot->Right);
}
}
//二叉树的深度
int TreeDepth(Node* BinaryRoot)
{
if (BinaryRoot)
{
return TreeDepth(BinaryRoot->Left) > TreeDepth(BinaryRoot->Right) ? TreeDepth(BinaryRoot->Left) + 1 : TreeDepth(BinaryRoot->Right) + 1;
}
if (BinaryRoot == NULL)
{
return 0;
}
}
//二叉树叶子节点数
int LeafNum(Node* BinaryRoot)
{
if (!BinaryRoot)
{
return 0;
}
else if ((BinaryRoot->Left == NULL) && (BinaryRoot->Right == NULL))
{
return 1;
}
else
{
return (LeafNum(BinaryRoot->Left) + LeafNum(BinaryRoot->Right));
}
}
int main()
{
Node *BinaryRoot = NULL;
BinaryRoot = createBinaryTree();
cout<<"创建二叉树"<<endl;
cout << "二叉树总节点数:" << NodeNum(BinaryRoot) << endl;
cout << "二叉树深度:" << TreeDepth(BinaryRoot) << endl;
cout << "二叉树叶子节点数:" << LeafNum(BinaryRoot) << endl;
cout << "先序遍历:" << endl;
PreOrderTraverse(BinaryRoot);
cout << endl;
cout << "中序遍历:" << endl;
InOrderTraverse(BinaryRoot);
cout << endl;
cout << "后序遍历:" << endl;
LastOrderTraverse(BinaryRoot);
cout << endl;
return 0;
}
二叉树-----建立、先序遍历、中序遍历、后序遍历、求结点数、求度、求叶子结点数
猜你喜欢
转载自blog.csdn.net/weixin_39916039/article/details/81739062
今日推荐
周排行