二叉树三种建树方式【普通】【前序】【完美】

#include
#include
#include<stdlib.h>
#include<time.h>
#include
#include
using namespace std;

typedef struct node* tree;

struct node
{
long int data;
node* left;
node* right;
};

tree buildtree1()//普通建树,就是根据已知将各个位置填写
{
tree root = new node;

root->data = 1;

root->left = new node;

root->right = new node;

root->left->data = 2;

root->right->data = 3;

return root;

}

tree buildtree2(tree root)//先序建树,以左边为先序,先输入左边的
{

int c;

cin >> c;

if (c == -1)
{
	return NULL;
}

root->data = c;

root->left = NULL;
root->right = NULL;

buildtree2(root->left);

buildtree2(root->right);

return root;

}

tree buildtree3(int a[], int n)//完美二叉树建立
{
tree root = new node[n+1];
//tree root = (tree)malloc(sizeof(node) * (n + 2));
for (int i=1; i <= n; i++)
{
root[i].data = a[i];
root[i].left = NULL;
root[i].right = NULL;
}

for (int i = 1; i <= n / 2; i++)
{
	if(2*i<=n)
	root[i].left = &root[i * 2];
	if((2*i+1)<=n)
	root[i].right = &root[i * 2 + 1];
}

return &root[1];

}

void cengxu(tree root)//层序遍历
{
queueque;

if (root == NULL)
{
	return;
}

que.push(root);

while (!que.empty())
{
	cout << que.front()->data << " ";

	if (que.front()->left) que.push(que.front()->left);
	if (que.front()->right)que.push(que.front()->right);
	que.pop();
}

}

int main()
{
int a[11] = { 0,1,2,3,4,5,6,7,8,9,10 };

tree root=buildtree3(a, 10);

cengxu(root);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值