leetcode_question_109 Convert Sorted List to Binary Search Tree
2013-09-23 00:16
489 查看
Given a singly linked list where elements are sorted in ascending order, convert it to a
height balanced BST.
Recursive:
height balanced BST.
Recursive:
/** * 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: void findmid(ListNode* head, ListNode* end, ListNode* &mid) { if(head == NULL){mid=NULL; return;} if(head->next == end){mid=head; return;} ListNode* pre = head; mid = head; while(pre->next != end) { pre = pre->next; if(pre->next != end) pre= pre->next; else break; mid = mid->next; } } TreeNode *tobst(ListNode* head, ListNode* tail) { if(head == tail)return NULL; if(head->next == tail) { int val = head->val; delete head; return new TreeNode(val); } ListNode* mid; findmid(head, tail, mid); TreeNode* tmp = new TreeNode(mid->val); tmp->left = tobst(head, mid); if(mid->next) tmp->right = tobst(mid->next, tail); delete mid; return tmp; } TreeNode *sortedListToBST(ListNode *head) { // Start typing your C/C++ solution below // DO NOT write int main() function if(head==NULL)return NULL; return tobst(head,NULL); } };
相关文章推荐
- LeetCode 109 Convert Sorted List to Binary Search Tree
- LeetCode: Convert Sorted List to Binary Search Tree [109]
- *Leetcode 109 Convert Sorted List to Binary Search Tree
- Leetcode 109, Convert Sorted List to Binary Search Tree
- LeetCode109 Convert Sorted List to Binary Search Tree
- Leetcode#109 Convert Sorted List to Binary Search Tree
- LeetCode 109 Convert Sorted List to Binary Search Tree
- Leetcode 109 Convert Sorted List to Binary Search Tree
- leetcode 109 —— Convert Sorted List to Binary Search Tree
- leetcode[109]Convert Sorted List to Binary Search Tree
- leetCode 108,109:Convert Sorted Array/List to Binary Search Tree
- leetcode-109-Convert Sorted List to Binary Search Tree
- 109. Convert Sorted List to Binary Search Tree LeetCode
- 109 Convert Sorted List to Binary Search Tree [Leetcode]
- Leetcode109——Convert Sorted List to Binary Search Tree
- [LeetCode]109 Convert Sorted List to Binary Search Tree
- [LeetCode 109] - 将已排序链表转换为二叉搜索树 (Convert Sorted List to Binary Search Tree)
- [LeetCode109]Convert Sorted List to Binary Search Tree
- leetcode-109 Convert Sorted List to Binary Search Tree
- leetcode109~Convert Sorted List to Binary Search Tree