题目描述:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
解题思路:
- 首先理解题意,这道题的意思就是说将一个升序排列的链表转换成一个高度平衡的二叉树
- 对于平衡二叉树我们脑子里的第一个反应应该就是递归了
- 这题也不例外,我们首先找到链表中间位置的节点,将它设为根节点,然后递归处理它的左右节点
代码如下:
public TreeNode sortedListToBST(ListNode head) {
// 首先处理链表的特殊情况,同时也是递归的终止条件
if(head == null) return null;
if(head.next == null) return new TreeNode(head.val);
ListNode fast = head.next;
ListNode slow = head;
// 找到链表的中间节点
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
// 递归处理链表中的节点,将其建成树形结构
TreeNode root = new TreeNode(slow.next.val);
root.right = sortedListToBST(slow.next.next);
slow.next = null;
root.left = sortedListToBST(head);
return root;
}