码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode dfs Convert Sorted List to Binary Search Tree

时间:2014-10-12 00:00:36      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   for   sp   

Convert Sorted List to Binary Search Tree

 Total Accepted: 21420 Total Submissions: 78476My Submissions

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



题意:把有序单链表转换为二叉查找树
思路:
用链表中心作为当作二叉树的根,
链表的前半段作为左子树、后半段作为右子树。
可用递归实现
复杂度:时间O(n* log n),空间O(log n)

TreeNode * dfs(ListNode *head, int size){
	if(size <= 0) return NULL;
	if(size == 1) return new TreeNode(head->val);


	ListNode *cur = head;
	for(int i = 0; i < size/2; ++i){
		cur = cur->next;
	}
	TreeNode *root = new TreeNode(cur->val);
	root->left = dfs(head, size/2);
	root->right = dfs(cur->next, size - size/2 - 1 );
	return root;
}


TreeNode *sortedListToBST(ListNode *head) {
	ListNode *cur = head;
	int size = 0;
	while(cur){
		++size;
		cur = cur->next;
	}
	return dfs(head, size);
}


leetcode dfs Convert Sorted List to Binary Search Tree

标签:style   blog   http   color   io   os   ar   for   sp   

原文地址:http://blog.csdn.net/zhengsenlie/article/details/39999345

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