您的位置:首页 > 编程语言 > C语言/C++

二叉树的C++指针实现

2016-03-07 21:12 661 查看
二叉树的C++用指针实现,均有递归算法实现,能够实现以下功能。

1. 输入数字建立一个二叉树,输入-1表示为空节点。

2.前中后序遍历(中左右,左中右,左右中)。

3.计算二叉树节点的数量。

4.计算二叉树的深度。

5.二叉树插入数据,可以用作排序,小的放在节点左边,大的放在节点右边。

#include<iostream>

using namespace std;

//二叉树的指针实现

struct Binode//二叉树的节点
{
int data;
Binode *left, *right;//左右子树
};

//创建一个二叉树
void createBtree(Binode *&root)
//这里要使用传递指针的引用,因为要给变指针指向内存中的值,与链表不一样,链表要改变指针指向的位置
{
int nodeValue;
cout << "输入根节点值" << endl;
cin >> nodeValue;

if (-1==nodeValue)
{
root = NULL;//是否要指针
}
else
{
root = new Binode;
root->data = nodeValue;
createBtree(root->left);
createBtree(root->right);
}
}

//二叉树的遍历,有先序,中序和后序三种
void visit(Binode *&T)//访问节点
{
if(T->data != -1)
{
cout <<T->data<< endl;
}
}

void preOrder(Binode *&T)//先序遍历
{

if (T != NULL)
{
visit(T);
preOrder(T->left);
preOrder(T->right);
}

}

void inOrder(Binode *&T)//中序遍历
{
if (T != NULL)
{
inOrder(T->left);
visit(T);
inOrder(T->right);
}
}

void postOrder(Binode *&T)//后序遍历
{
if (T != NULL)
{
postOrder(T->left);
postOrder(T->right);
visit(T);
}
}

int countNode(Binode *&T)//计算节点的数量
{
if (T == NULL)
{
return 0;
}
return 1 + countNode(T->left) + countNode(T->right);//递归
}

int countDepth(Binode *&T)
{
if (T == NULL)
return -1;

int h1 = countDepth(T->left);
int h2 = countDepth(T->right);

if (h2 > h1){ return h2 + 1; }
return h1 + 1;
}

//插入元素
Binode *insertNode(Binode *&T,int idata)//idata为插入的数据
{
Binode *p = new Binode;
p->data = idata;
p->left = NULL;
p->right = NULL;//初始化新增的节点

if (NULL == T)
{
T = p;
}
else if (idata<T->data)
{
T->left = insertNode(T->left, idata);
}
else
{
T->right = insertNode(T->right, idata);
}

return T;
}

int main()
{
Binode *p=NULL;//初始化节点

//createBtree(p);
int a[] = {3,2,4,1,5};

for (int i = 0; i < 5; i++)
{
p = insertNode(p, a[i]);
}

cout << "中序遍历" << endl;
inOrder(p);

system("pause");
return 0;
}


测试用例是输入5个乱序数字3,2,4,1,5,按照二叉排序,中序遍历应该输出顺序。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: