[leetcode] 109. Convert Sorted List to Binary Search Tree

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)

参考文献

[编程题]convert-sorted-list-to-binary-search-tree

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值