Convert Sorted List to Binary Search Tree [LeetCode]
2013-11-29 07:41
441 查看
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Solution:
Solution:
TreeNode *sortedListToBST(ListNode *head) { if(head == NULL) return NULL; if(head->next == NULL) return new TreeNode(head->val); ListNode * current = head; int size = 0; while(current != NULL){ size ++; current = current->next; } current = head; int median = size / 2; int count = 0; ListNode * median_node = NULL; ListNode * pre_node = NULL; while(current != NULL){ if(count == median){ median_node = current; pre_node->next = NULL; break; } count ++; pre_node = current; current = current->next; } TreeNode * root = new TreeNode(median_node->val); root->left = sortedListToBST(head); root->right = sortedListToBST(median_node->next); return root; }
相关文章推荐
- [leetcode] 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】Convert Sorted List to Binary Search Tree
- leetcode_question_109 Convert Sorted List to Binary Search Tree
- [Leetcode] Convert Sorted List to Binary Search Tree Solution
- 【leetcode】Convert Sorted Array/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 109 Convert Sorted List to Binary Search Tree
- leetcode109~Convert Sorted List to Binary Search Tree
- LeetCode解题报告——Convert Sorted List to Binary Search Tree & Populating Next Right Pointers in Each Node & Word Ladder
- [LeetCode109]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 Array to Binary Search Tree && Convert Sorted List to Binary Search Tree
- [LeetCode] Convert Binary Search Tree to Sorted Doubly Linked List 将二叉搜索树转为有序双向链表
- LeetCode Convert Sorted List to Binary Search Tree
- LeetCode:Convert Sorted List to Binary Search Tree