码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-12-15 00:45:07      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:nal   recursion   class   数据   ast   递归   cas   star   序列   

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. 排序列表转换为二分查找树

标签:nal   recursion   class   数据   ast   递归   cas   star   序列   

原文地址:http://www.cnblogs.com/kanekiken/p/8040545.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!