leetcode Convert Sorted List to Binary Search Tree
2013-05-07 22:04
411 查看
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
O(n) solution
O(n) solution
BinaryTree* sortedListToBST(ListNode *& list, int start, int end) { if (start > end) return NULL; // same as (start+end)/2, avoids overflow int mid = start + (end - start) / 2; BinaryTree *leftChild = sortedListToBST(list, start, mid-1); BinaryTree *parent = new BinaryTree(list->data); parent->left = leftChild; list = list->next; parent->right = sortedListToBST(list, mid+1, end); return parent; } BinaryTree* sortedListToBST(ListNode *head, int n) { return sortedListToBST(head, 0, n-1); }
相关文章推荐
- LeetCode Convert Sorted List to Binary Search Tree
- 5 Convert Sorted List to Binary Search Tree_Leetcode
- leetcode 109 —— Convert Sorted List to Binary Search Tree
- [LeetCode]Convert Sorted List to Binary Search Tree
- 【Leetcode】Convert Sorted List to Binary Search Tree
- Leetcode:Convert Sorted List to Binary Search Tree
- leetcode Convert Sorted List to Binary Search Tree
- LeetCode:Convert Sorted List to Binary Search Tree
- [leetcode] Convert Sorted List to Binary Search Tree
- leetcode[109]:Convert Sorted List to Binary Search Tree
- LeetCode-Convert Sorted List to Binary Search Tree
- LeetCode:Convert Sorted Array(List) to Binary Search Tree
- 【leetcode】【单链表】【109】Convert Sorted List to Binary Search Tree
- LeetCode刷题(C++)——Convert Sorted List to Binary Search Tree(Normal)
- LeetCode109 Convert Sorted List to Binary Search Tree
- [LeetCode]题解(python):109-Convert Sorted List to Binary Search Tree
- Leetcode习题:Convert Sorted List to Binary Search Tree
- LeetCode Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree [LeetCode]
- [LeetCode 109] - 将已排序链表转换为二叉搜索树 (Convert Sorted List to Binary Search Tree)