LeetCode算法题109:有序链表转换二叉搜索树解析

给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。

本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。

示例:

给定的有序链表: [-10, -3, 0, 5, 9],

一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:

      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) {
        return helper(head, NULL);
    }
    TreeNode* helper(ListNode* head, ListNode* tail){
        if (head == tail) return NULL;
        ListNode *slow = head, *fast = head;
        while(fast!=tail && fast->next!=tail){
            slow = slow->next;
            fast = fast->next->next;
        }
        TreeNode *cur = new TreeNode(slow->val);
        cur->left = helper(head, slow);
        cur->right = helper(slow->next, tail);
        return cur;
    }
};

python3源代码:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def sortedListToBST(self, head: ListNode) -> TreeNode:
        return self.helper(head, None)
    
    def helper(self, head, tail):
        if head==tail:
            return None
        slow = head
        fast = head
        while fast!=tail and fast.next!=tail:
            slow = slow.next
            fast = fast.next.next
        cur = TreeNode(slow.val)
        cur.left = self.helper(head, slow)
        cur.right = self.helper(slow.next, tail)
        return cur
    

猜你喜欢

转载自blog.csdn.net/x603560617/article/details/87931595