Covert sorted list to binary search tree--LeetCode

本文详细介绍了如何将一个有序的链表转换为平衡的二叉搜索树(BST)。通过使用链表的特性,实现了一个高效的算法来找到链表的中间节点,并递归地构建BST。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:把一个有序的链表转换为BST

思路:和上面的一样,只不过这里需要注意查找链表中间点的方法

程序中只有最后三个函数有用

#include <iostream>
using namespace std;
/*
将一个有序的链表 转换为二叉平衡树 BST 
*/

/*
思路:这个和上面将有序的数组装换为BST非常相似 
都是采用同样的方法 只是这里查找链表的中间节点
是一个很麻烦的事情 
*/
typedef struct list_node List;
typedef struct bst_node BST;

struct list_node 
{
	int value;
	List* next;	
};

struct bst_node
{
	int value;
	BST* left;
	BST* right;
};
 
void print_list(List* list)  
{  
    List* tmp=list;  
    while(tmp != NULL)  
    {  
        cout<<tmp->value<<endl;  
        tmp = tmp->next;   
    }  
}  
  
/* 
初始化List  将从1~n的数字插入到链表中  
*/  
void Init_List(List*& head,int* array,int n)  
{  
    head = NULL;  
    List* tmp;  
    List* record;  
    
    for(int i=1;i<=n;i++)  
    {  
        tmp = new List;  
        tmp->next = NULL;  
        tmp->value = array[i-1];  
        if(head == NULL)  
        {  
            head = tmp;  
            record = head;  
        }  
        else  
        {  
            record->next = tmp;  
            record = tmp;  
        }  
    }  
}  
  
int Len_list(List* list)  
{  
    if(list == NULL)  
        return 0;  
    else  
        return Len_list(list->next)+1;  
}  
  

void print_bintree(BST* root)
{
	if(root != NULL)
	{
		print_bintree(root->left);
		cout<<root->value<<endl;
		print_bintree(root->right);
	}
}


/*
从一个链表的头部和尾部找到中间节点 这里的tail是组成区间的链表的最后一个节点的下一个节点 
*/
List* getMid(List* list,List* head,List* tail)
{
	if(head == NULL)
		return NULL;
	if(head == tail)
		return  NULL;
	List* slow = head;
	List* fast = head->next;
	while(fast!=NULL && fast != tail)
	{
		slow = slow->next;
		fast = fast->next;
		if(fast != NULL && fast != tail)
			fast = fast->next;
	}
	return slow;
}
 

BST* helper(List* list,List* head,List* tail)
{
	BST* root = NULL;
	if(head == NULL)
		return NULL;
	else
	{
		List* mid = getMid(list,head,tail);
		
		if(mid != NULL)
		{
			BST* root = new BST;
			root->left = NULL;
			root->right = NULL;
		 	root->value = mid->value;
			root->left = helper(list,head,mid);
	 	 	root->right = helper(list,mid->next,tail);
		  	return root;	
		}
		return NULL;
	}
}

BST* ListCreateBST(List* list)
{
	if(list == NULL)
		return NULL;
	return helper(list,list,NULL);
}


int main()
{
	
	int array[15];
	int i;
	for(i=0;i<sizeof(array)/sizeof(int);i++)
		array[i] = i+1;
	List* list;
	Init_List(list,array,sizeof(array)/sizeof(int));
	BST* root = ListCreateBST(list);
	
	print_bintree(root);
	return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值