标签:des style color io ar for art 代码 sp
Problem Description:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
分析:很容易想到的一种解法是将链表中所有的元素保存到数组中,然后每次取中间值进行构造,时间复杂度为O(n),空间复杂度为O(n)。具体实现如下:
/** * 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* createTree(vector<ListNode *> &listvec,int begin,int last) { if(begin>last) return NULL; if(begin==last) { int val=listvec[begin]->val; TreeNode *head=new TreeNode(val); return head; } else { int mid=(begin+last)/2; int val=listvec[mid]->val; TreeNode *head=new TreeNode(val); head->left=createTree(listvec,begin,mid-1); head->right=createTree(listvec,mid+1,last); return head; } } TreeNode *sortedListToBST(ListNode *head) { TreeNode *Treehead=NULL; if(head==NULL) return Treehead; vector<ListNode *> listvec; ListNode *p=head; while(p) { listvec.push_back(p); p=p->next; } Treehead=createTree(listvec,0,listvec.size()-1); return Treehead; } };
TreeNode *sortedListToBST(ListNode *head) { int len = 0; ListNode * node = head; while (node != NULL) { node = node->next; len++; } return buildTree(head, 0,len-1); } TreeNode *buildTree(ListNode *&node, int start, int end) { if (start > end) return NULL; int mid = start + (end - start) / 2; TreeNode *left = buildTree(node, start, mid-1); TreeNode *root = new TreeNode(node->val); root->left = left; node = node->next; root->right = buildTree(node, mid+1, end); return root; }
Leetcode--Convert Sorted List to Binary Search Tree
标签:des style color io ar for art 代码 sp
原文地址:http://blog.csdn.net/longhopefor/article/details/39082653