标签:
题目描述:(链接)
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
解题思路:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 /** 10 * Definition for a binary tree node. 11 * struct TreeNode { 12 * int val; 13 * TreeNode *left; 14 * TreeNode *right; 15 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 16 * }; 17 */ 18 class Solution { 19 public: 20 TreeNode* sortedListToBST(ListNode* head) { 21 return sortedListToBST(head, len(head)); 22 } 23 private: 24 TreeNode *sortedListToBST(ListNode *head, int len) { 25 if (len == 0) return nullptr; 26 if (len == 1) return new TreeNode(head->val); 27 28 int mid = len / 2; 29 TreeNode *root = new TreeNode((afterNthNode(head, mid))->val); 30 root->left = sortedListToBST(head, mid); 31 root->right = sortedListToBST(afterNthNode(head, mid + 1), len - mid - 1); 32 33 return root; 34 } 35 36 int len(ListNode *head) { 37 int n = 0; 38 while (head) { 39 head = head->next; 40 ++n; 41 } 42 43 return n; 44 } 45 46 ListNode *afterNthNode(ListNode *head, int n) { 47 while (n--) { 48 head = head->next; 49 } 50 51 return head; 52 } 53 };
[LeetCode]Convert Sorted List to Binary Search Tree
标签:
原文地址:http://www.cnblogs.com/skycore/p/5055392.html