leetcode之Convert Sorted List to Binary Search Tree

题目大意:

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

意思就是:

给定一个单向链表, 链表中的元素按升序排序. 请把该链表转换成平衡搜索树

解题思路:

递归方法. 先从链表中间折断,中间元素作为root,  继续对左右两半链表进行递归折断, 左右两边的left_root和right_root分别作为root的左右孩子.  一直递归, 直到所有元素都被分到搜索树中.

代码如下:

/**
 * 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) {
 			if(!head){
				return NULL;
			}
			if(!head->next){
				TreeNode* node = new TreeNode(head->val);
				return node;
			}
			ListNode* currentL = head;
			vector<ListNode*> storage;
			while(currentL){
				storage.push_back(currentL);
				currentL = currentL->next;
			}
			vector<ListNode*>::size_type length = storage.size();
			TreeNode* root = new TreeNode(storage[length/2]->val);
			TreeNode* leftT = dfsTravel(root, storage, 0, length/2-1);
			root->left = leftT;
			TreeNode* rightT = dfsTravel(root, storage, length/2+1, length-1);
			root->right = rightT;
			return root;
    }
    	TreeNode* dfsTravel(TreeNode* node, vector<ListNode*>& storage, int start, int end){
			if(end>=start){
				TreeNode* result = new TreeNode(storage[(end+1-start)/2+start]->val);
				TreeNode* leftT = dfsTravel(result, storage, start, (end-start+1)/2-1+start);
				result->left = leftT;
				TreeNode* rightT = dfsTravel(result, storage, (end-start+1)/2+1+start, end);
				result->right = rightT;
				return result;
			}
			else if(end < start){
				return NULL;
			}
		}
};


你可能感兴趣的:(LeetCode,C++,算法)