英文原题
Given the head of 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.
分析
用递归的方法,把这个问题拆成多个子问题。题目给出的链表是排好序的,同时题目要求我们构建高度平衡二叉树,很容易想到取链表的中间点为根节点左边为左子树右边为右子树,接下来就是把左右子链表放入递归里面继续构建二叉树。 至于找中间点的方法是用快慢指针,慢指针一次走一步,快指针一次两步,等快指针到链表最后的时候慢指针就正好是链表中点了。
python 代码
1 | class Solution: |