Description
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted linked list: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5
分析一
题目的意思是:给了一个有序链表,转换成一棵二叉查找树。
- 通过快慢指针法找到中点,然后将其作为跟节点;然后根据中点,把分成左右链表,递归的建树。
C++实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
if(!head){
return NULL;
}
if(!head->next){
return new TreeNode(head->val);
}
ListNode* slow=head;
ListNode* fast=head;
ListNode* last=slow;
while(fast->next&&fast->next->next){
fast=fast->next->next;
last=slow;
slow=slow->next;
}
fast=slow->next;
last->next=NULL;
TreeNode* root=new TreeNode(slow->val);
if(head!=slow){
root->left=sortedListToBST(head);
}
root->right=sortedListToBST(fast);
return root;
}
};
分析二
- 解法二跟解法一的思想是一样的,只是我们把中间结点也作为参数传导了,然后在写代码上稍稍有点区别。
代码二
/**
* 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 *sortedListToBST(ListNode *head) {
return BST(head,NULL);
}
TreeNode *BST(ListNode *head,ListNode *tail){
if(head==tail){
return NULL;
}
ListNode *slow=head;
ListNode *fast=head;
while(fast!=tail&&fast->next!=tail){
slow=slow->next;
fast=fast->next->next;
}
TreeNode *root=new TreeNode(slow->val);
root->left=BST(head,slow);
root->right=BST(slow->next,tail);
return root;
}
};
Python实现
需要通过快慢指针找到中点,然后通过递归的方式构建左右子树,如果对链表操作比较熟练就能写出来。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def get_median(self, left,right):
fast = left
slow = left
while fast !=right and fast.next!=right:
fast = fast.next.next
slow = slow.next
return slow
def create_tree(self, left, right):
if left==right:
return None
mid = self.get_median(left, right)
root = TreeNode(mid.val)
root.left = self.create_tree(left,mid)
root.right = self.create_tree(mid.next, right)
return root
def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:
return self.create_tree(head, None)