/**
* 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* Convert(ListNode*& node, int start, int end) {
if(start > end) return NULL;
int mid = start + (end - start) / 2;
TreeNode* leftChild = Convert(node, start, mid - 1);
TreeNode* parent = new TreeNode(node->val);
parent->left = leftChild;
node = node->next;
parent->right = Convert(node, mid + 1, end);
return parent;
}
TreeNode *sortedListToBST(ListNode *head) {
if(!head) return NULL;
int length = 0;
ListNode* node = head;
while(node){
++length;
node = node->next;
}
TreeNode* newHead = Convert(head, 0, length - 1);
return newHead;
}
};LeetCode 109. Convert Sorted List to Binary Search Tree
最新推荐文章于 2021-01-12 00:53:34 发布
本文介绍了一种将已排序的单链表转换为高度平衡二叉搜索树的方法。通过递归地选择中间元素作为根节点,并将左右部分递归地构建为子树,确保了树的高度平衡。该方法利用了链表的有序特性,有效地实现了转换。
411

被折叠的 条评论
为什么被折叠?



