Problem
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Example
2
1->2->3 => / \1 3
Note
用递归的方法来做,首先新建cur
结点来复制head
结点,然后计算链表head
的长度,调用helper(start, end)
函数建立平衡BST。
当链表为空时,helper()
中出现start
大于end
,返回null
。然后计算中点mid
,以mid
为界分别递归构建左右子树。顺序是,左子树-->根结点-->右子树
。由于根节点root
是直接取cur.val
构建,当前的cur
已经被取用。所以在下一次递归构建右子树之前,要让cur
指向cur.next
。最后将root
和左右子树相连,返回root
。
Solution
public class Solution {ListNode cur;public TreeNode sortedListToBST(ListNode head) { cur = head;int len = 0;while (head != null) {head = head.next;len++;}return helper(0, len-1);}public TreeNode helper(int start, int end) {if (start > end) return null;int mid = start+(end-start)/2;TreeNode left = helper(start, mid-1);TreeNode root = new TreeNode(cur.val);cur = cur.next;TreeNode right = helper(mid+1, end);root.left = left;root.right = right;return root;}
}