有序链表转换为平衡二叉树(BST)

有序单链表转换为平衡二叉树。

TreeNode *buildTree(ListNode *&list,int n)
{
	if (n == 0)
		return NULL;
	
	TreeNode *root = new TreeNode(0);
	root->left = buildTree(list,n / 2);
	root->val = list->val;
	list = list->next;
	root->right = buildTree(list,n - n / 2 - 1);
	return root;
}

TreeNode* sortedListToBST(ListNode* head) 
{
	int size = 0;
	ListNode *p = head;
	while (p)
	{
		size++;
		p = p->next;
	}
	p = head;
	ListNode *list = head;
	return buildTree(list,size);

}

    原文作者:平衡二叉树
    原文地址: https://blog.csdn.net/yang20141109/article/details/51819614
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞