标签:
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