将有序链表变为二叉搜索树

  • 问题描述
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
给定一个单链表,其中元素按升序排序,将其转换为高度平衡的BST。

  • 问题分析
二叉搜索树(二叉排序树):左子树结点一定比父结点小,右子树结点一定比父结点大。
for example:
排序后的单链表为:0->1->2->3->4->5->6->7->8->9->NULL;
转换的BST为:


  • 解题思路
①使用快慢指针,快指针指向链表尾时,慢指针所指向的节点为第一个根节点;
②从根节点处将链表换分为前后两段,把根节点前的那段链表记为Lf,根节点后的那段链表记为Lb;
③根节点的左节点为Lf的根节点,右节点为Lb的根节点。递归第①步。

  • 代码实现

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
	TreeNode *sortedListToBST(ListNode *head) {
		return BST(head, NULL);
	}
	TreeNode *BST(ListNode *head, ListNode *tail)//递归函数
	{
		if (head == tail)
			return NULL;

		ListNode *fast = head;
		ListNode *slow = head;
		while (fast != tail && fast->next != tail)
		{
			slow = slow->next;
			fast = fast->next->next;
		}
		TreeNode *root = new TreeNode(slow->val);//创建根节点
		root->left = BST(head, slow);
		root->right = BST(slow->next, tail);

		return root;
	}
};


猜你喜欢

转载自blog.csdn.net/ananbei/article/details/80630440