Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
好吧,还是用递归!
/**
* 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 *buildTree(ListNode *&head, int begin, int end) {
if(begin > end) return NULL;
int mid = (begin + end) / 2;
TreeNode *root = new TreeNode(0);
root->left = buildTree(head, begin, mid - 1);
root->val = head->val;
head = head->next;
root->right = buildTree(head, mid + 1, end);
return root;
}
TreeNode *sortedListToBST(ListNode *head) {
ListNode *temp = head;
int length = 0;
while(temp != NULL) {
length ++;
temp = temp->next;
}
return buildTree(head, 0, length - 1);
}
};
本文介绍了一种通过递归方法将排序链表转换为高度平衡二叉搜索树的方法,详细解释了如何利用链表节点构建二叉搜索树,确保树的高度平衡。
124

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



