每日一题 2019 - 04 - 25
题目:
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:
1 | Given the sorted linked list: [-10,-3,0,5,9], |
解法:
这个题让在给定的链表序列里面构造出一颗平衡二叉搜索树,也即每一颗子树的左右子树高度差不大于 1 ,由于给定的序列是排序好的序列,所以可以直接使用二分法来完成构建;
- 每一次取出当前序列的中点,把当前序列的中点当做根节点,然后使用左右两边的序列对左右两边的子树进行构建;
- 重复上述过程,直到左右两边的序列遍历完毕,即可完成任务;
代码:
1 | /** |