106. 排序列表转换为二分查找树

Posted Carlos

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了106. 排序列表转换为二分查找树相关的知识,希望对你有一定的参考价值。

106. 排序列表转换为二分查找树 

 

给出一个所有元素以升序排序的单链表,将它转换成一棵高度平衡的二分查找树

样例
               2
1->2->3  =>   /              1   3
标签 
 
/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */


class Solution {
public:
       /**
     * @param head: The first node of linked list.
     * @return: a tree node
     */
    TreeNode *sortedListToBST(ListNode *head) {
        // write your code here
     	//用递归 
    	TreeNode* root = nullptr;
    	if (head != nullptr)
    	{
    		ListNode *left = nullptr, *right = nullptr;
    		root = new TreeNode(dichotomyList(head, left, right));
    		root->left = sortedListToBST(left);
    		root->right = sortedListToBST(right);
    	}
    }

    int dichotomyList(ListNode *head, ListNode *&left, ListNode *&right) {
       	if (head->next != nullptr)
    	{
    		ListNode *fast = head, *slow = head, *temp = head;
    		while (fast != nullptr && fast->next != nullptr)
    		{
    			temp = slow;
    			slow = slow->next;
    			fast = fast->next->next;
    		}
    		temp->next = nullptr;
    		left = head;
    		right = slow->next;
    		return slow->val;
    	}
    	else
    	{
    		left = nullptr;
    		right = nullptr;
    		return head->val;
    	}
    }
};

  

以上是关于106. 排序列表转换为二分查找树的主要内容,如果未能解决你的问题,请参考以下文章

《图解算法》--二分查找选择排序递归

数据结构简单谈一谈二分法和二叉排序树BST查找的比较

LeetCode 34 在排序树组中查找元素的第一个和最后一个位置[二分法] HERODING的LeetCode之路

数据结构与算法-查找算法

数据查找之80-20原则的JavaScript代码实现

查找算法总结(二分查找/二叉查找树/红黑树/散列表)