创建一个具有十个节点的完全二叉树

 创建一个具有十个节点的完全二叉树(注意是完全二叉树)要求:先定义二叉树的节点,该程序返回创建的二叉树的根节点地址

zhibin@zhibin-virtual-machine:~/code_Learning/code_2024_1_19/lesson$ gcc -o test1 test1.c
zhibin@zhibin-virtual-machine:~/code_Learning/code_2024_1_19/lesson$ ./test1
8 9 4 10 5 2 6 7 3 1 zhibin@zhibin-virtual-machine:~/code_Learning/code_2024_1_19/lesson$ 
第一次调用 BuildTree:
进入函数后,检查 current_index <= node_count,是真,继续执行。
创建一个新的节点,值为 1,将其赋值给树根 root。

然后,递归调用 BuildTree(&((*root)->leftchild), 2 * root_num, node_count, 2 * current_index),进入左子树的递归。
这时,参数为 (&root->leftchild, 2, 10, 2)。

进入左子树的递归,检查条件,继续执行,创建节点值为 2,赋值给左子树的根节点。
递归调用左子树的递归,参数为 (&leftchild, 4, 10, 4)。

第二次调用 BuildTree:
进入函数,创建节点值为 4,赋值给左子树的左子树的根节点。
递归调用左子树的左子树的递归,参数为 (&leftchild->leftchild, 8, 10, 8)。

以此类推,直到 current_index > node_count 时,递归停止。
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include<string.h>

typedef int TreeDataType;
typedef struct TreeNode
{
	TreeDataType data;
	struct TreeNode* leftchild;
	struct TreeNode* rightchild;
}TreeNode;
TreeNode* BuyTreeNode(TreeDataType x)
{
	TreeNode* newtreenode = (TreeNode*)malloc(sizeof(TreeNode));
	if(newtreenode  == NULL)
	{
		perror("malloc");
		exit(-1);
	}
	newtreenode->data = x;
	newtreenode->leftchild = NULL;
	newtreenode->rightchild = NULL;
	return newtreenode;
}
void BuildTree(TreeNode** root,int root_num,int node_count,int current_index)
{
	if(current_index <= node_count)
	{
		//1 2 3 4 5 6 7 8 9 10
		//创建root
	    *root = BuyTreeNode(root_num);  	
		BuildTree(&((*root)->leftchild),2*root_num,node_count,2*current_index);
		BuildTree(&((*root)->rightchild),2*root_num+1,node_count,2*current_index+1);
	}
}
void TreePrint(TreeNode* root)
{
	if(root != NULL)
	{
		TreePrint(root->leftchild);
		TreePrint(root->rightchild);
		printf("%d ",root->data);
	}
}
int main()
{
	TreeNode* root = NULL;
	BuildTree(&root,1,10,1);
	TreePrint(root);
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值