数据结构学习 之 二叉树的建立前序中序后序遍历

#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;
}

该树如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值