标签:style blog io ar color sp for on div
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
解题思路:找到链表的中点,作为根,前端作为左子树,后端作为右子树,并对前后做递归操作。
/** * 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 *getbTree(ListNode *head,int start,int end) { if(start<=end) { int mid = (start+end)>>1; ListNode *work = head; ListNode *rstart=NULL; for(int i=start;i<mid;i++) { work = work->next; } rstart = work->next; TreeNode *node = new TreeNode(work->val); node->left = getbTree(head,start,mid-1); node->right = getbTree(rstart,mid+1,end); return node; } else return NULL; } TreeNode *sortedListToBST(ListNode *head) { if(head==NULL)return NULL; int len = 0; ListNode *p = head; while(p) { ++len; p=p->next; } return getbTree(head,0,len-1); } };
LeetCode Convert Sorted List to Binary Search Tree
标签:style blog io ar color sp for on div
原文地址:http://www.cnblogs.com/55open/p/4161174.html