根据一个字符数组创建一个二叉树

根据一个字符数组创建一个二叉树

以’#‘代表节点为空,标识到非’#'创建节点并且赋值给这个节点

思想:递归


```c
struct node{
char data;
struct node*lchild;//指向左孩子
struct node * rchild;//指向右孩子

};
typedef struct node * ptree;//指向树根的指针

char treeData[] =“ABC##D##E#F#G##”; //假设这是定义的一个全局变量
int i ;//这也是一个全局变量,用于遍历treeData数组
/这是一个子函数/
ptree createBiTree(void)
{
ptree pbnode ;
char ch ;

	ch = treeData[i];
if( ch == '#' ){ pbnode = NULL;}
else 
{
	pbnode = (ptree)malloc(sizeof(struct node )); 
	if( pbnode == NULL )
	{
		printf("Out of space!\n");
		return pbnode;
	}
	pbnode->data = ch;
	i++;
	pbnode->lchild = createBiTree();//构造左子树  
	i++;
	pbnode->rchild = createBiTree();//构造右子树
	
		
}
return pbnode;
}

————————————————
版权声明:本文为CSDN博主「weixin_45329792」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_45329792/article/details/102810040

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,需要定义一个二叉堆类,包含堆的初始化、插入、删除等方法。然后,将字符串数组插入到堆,最后依次从堆删除元素,即可得到排序后的字符串数组。 以下是一个示例代码: ```java public class BinaryHeap { private String[] heapArray; private int maxSize; private int currentSize; public BinaryHeap(int maxSize) { this.maxSize = maxSize; this.currentSize = 0; this.heapArray = new String[maxSize]; } public boolean isEmpty() { return currentSize == 0; } public boolean insert(String value) { if (currentSize == maxSize) { return false; } heapArray[currentSize] = value; trickleUp(currentSize++); return true; } public String remove() { String root = heapArray[0]; heapArray[0] = heapArray[--currentSize]; trickleDown(0); return root; } private void trickleUp(int index) { int parent = (index - 1) / 2; String bottom = heapArray[index]; while (index > 0 && heapArray[parent].compareTo(bottom) < 0) { heapArray[index] = heapArray[parent]; index = parent; parent = (parent - 1) / 2; } heapArray[index] = bottom; } private void trickleDown(int index) { int largerChild; String top = heapArray[index]; while (index < currentSize / 2) { int leftChild = 2 * index + 1; int rightChild = leftChild + 1; if (rightChild < currentSize && heapArray[leftChild].compareTo(heapArray[rightChild]) < 0) { largerChild = rightChild; } else { largerChild = leftChild; } if (top.compareTo(heapArray[largerChild]) >= 0) { break; } heapArray[index] = heapArray[largerChild]; index = largerChild; } heapArray[index] = top; } } public class HeapSort { public static void main(String[] args) { String[] array = {"apple", "banana", "orange", "pear", "peach"}; BinaryHeap heap = new BinaryHeap(array.length); for (String s : array) { heap.insert(s); } for (int i = 0; i < array.length; i++) { array[i] = heap.remove(); } for (String s : array) { System.out.print(s + " "); } } } ``` 在这个示例,我们首先创建了一个二叉堆类 `BinaryHeap`,包含堆的初始化、插入、删除等方法。然后,我们创建了一个字符串数组,并将其插入到堆。最后,我们依次从堆删除元素,并将其存储到原数组,即可得到排序后的字符串数组
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值