数据结构学习 之 二叉树的建立前序中序后序遍历
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
struct BinaryTreeNode
{
int data;
BinaryTreeNode *leftchild; //左子树
BinaryTreeNode *rightchild; //右子树
};
//创建一棵二叉树
BinaryTreeNode *CreateBinartTree()
{
BinaryTreeNode *p;
int ch;
cin >> ch;
if( ch == 0)
{
p = NULL; //如果是叶子节点 那么左右均为0
}
else
{
p = (BinaryTreeNode*)malloc(sizeof(BinaryTreeNode));
p->data = ch;
p->leftchild = CreateBinartTree();
p->rightchild = CreateBinartTree(); //递归创建左子树和右子树
}
return p;
}
//对其进行先序遍历
void PreorderTraverse(BinaryTreeNode *root)
{
if(root)
{
cout << root->data << ' ';
PreorderTraverse(root->leftchild);
PreorderTraverse(root->rightchild);
}
}
//中序遍历
void InorderTraverse(BinaryTreeNode *root)
{
if(root)
{
InorderTraverse(root->leftchild);
cout << root->data << ' ';
InorderTraverse(root->rightchild);
}
}
//后序遍历
void LastOrderTraverse(BinaryTreeNode *root)
{
if(root)
{
LastOrderTraverse(root->leftchild);
LastOrderTraverse(root->rightchild);
cout << root->data << ' ';
}
}
//节点数目
int Nodenum(BinaryTreeNode *root)
{
if(root == NULL)
return 0;
else
return Nodenum(root->leftchild)+Nodenum(root->rightchild)+1;
}
//二叉树的深度
int Depath(BinaryTreeNode *root)
{
if(root == NULL)
{
return 0;
}
if(root)
{
return Depath(root->leftchild)>Depath(root->rightchild)?Depath(root->leftchild)+1:Depath(root->rightchild)+1;
}
}
//二叉树的叶子节点数目
int LeafNum(BinaryTreeNode *root)
{
if(!root)
{
return 0;
}
else if( (root->leftchild == NULL) && (root->rightchild == NULL))
{
return 1;
}
else
{
return (LeafNum(root->leftchild) + LeafNum(root->rightchild));
}
}
int main()
{
BinaryTreeNode *root = NULL;
root = CreateBinartTree();
cout << "二叉树建立成功" << endl;
cout << "节点总数:"<< Nodenum(root) << endl;
cout << "深度 :"<< Depath(root) << endl;
cout << "叶子节点:"<< LeafNum(root) << endl;
cout << "前序遍历结果:";
PreorderTraverse(root);
cout << endl;
cout << "中序遍历结果:";
InorderTraverse(root);
cout << endl;
cout << "后序遍历结果:";
LastOrderTraverse(root) ;
cout << endl;
return 0;
}
该树如下: