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

Convert Sorted List to Binary Search Tree

时间:2015-01-30 16:00:24      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

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

解题思路:采用中序排列的方法递归地决定每个结点的数值;

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
//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) {}
};
void ListToBST(vector<ListNode*>::iterator Begin, vector<ListNode*>::iterator End, TreeNode*&root)
{
	if (Begin==End)
		return;
	auto len = distance(Begin,End);
	if ((int)len == 1){
		root = new TreeNode((*Begin)->val);
		return;
	}
	auto Iter_mid = Begin;
	advance(Iter_mid, len / 2);
	root = new TreeNode((*Iter_mid)->val);
	ListToBST(Begin, Iter_mid, root->left);
	ListToBST(Iter_mid + 1, End, root->right);
}
TreeNode *sortedListToBST(ListNode *head) {
	vector<ListNode*>NodeVector;
	for (; head != NULL; head = head->next)
		NodeVector.push_back(head);
	TreeNode* Root = NULL;
	ListToBST(NodeVector.begin(), NodeVector.end(), Root);
	return Root;
}


Convert Sorted List to Binary Search Tree

标签:

原文地址:http://blog.csdn.net/li_chihang/article/details/43305803

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