LeetCode109 链表转二叉搜索树

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

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

Given the sorted linked list: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

题源:here;完整实现:here

思路:

两种方案,一种偷懒的方案,先转换为数组再转二叉树,另一种是利用生成树的先后顺序进行二叉树的构造。

1 偷懒版

TreeNode* sortedArrayToBST(vector& nums) {
	if (nums.size() == 0) return NULL;
	int mid = nums.size() / 2;
	TreeNode *root = new TreeNode(nums[mid]);
	vector leftNums(nums.begin(), nums.begin() + mid);
	vector rightNums(nums.begin() + mid + 1, nums.end());
	root->left = sortedArrayToBST(leftNums);
	root->right = sortedArrayToBST(rightNums);

	return root;
}

TreeNode* sortedListToBST(ListNode* head) {
	vector nums;
	ListNode *curr = head;
	while (curr){
		nums.push_back(curr->val);
		curr = curr->next;
	}

	return sortedArrayToBST(nums);
}

2 改变顺序版

TreeNode *sortedListToBST2(int left, int right, ListNode *&head){
	if (!head || left > right) return NULL;
	int mid = left + (right - left) / 2;
	TreeNode *leftNode = sortedListToBST2(left, mid - 1, head);
	TreeNode *root = new TreeNode(head->val);
	head = head->next;
	TreeNode *rightNode = sortedListToBST2(mid + 1, right, head);
	root->left = leftNode;
	root->right = rightNode;

	return root;
}

TreeNode* sortedListToBST2(ListNode* head) {
	int len = 0;
	ListNode *curr = head;
	while (curr){
		len++;
		curr = curr->next;
	}

	return sortedListToBST2(0, len, head);
}

 

你可能感兴趣的:(LeetCode实践)