树状结构的算法题时间复杂度是相对比较难的
因为有两种情况,一种是普通遍历,另一种是分治算法
而如Leetcode109. Convert Sorted List to Binary Search Tree
这题的代码如下
class Solution {
public TreeNode sortedListToBST(ListNode head) {
if (head == null) return null;
if (head.next == null) return new TreeNode(head.val);
ListNode preMid = findPreMid(head);
ListNode mid = preMid.next;
preMid.next = null;
TreeNode node = new TreeNode(mid.val);
node.left = sortedListToBST(head);
node.right = sortedListToBST(mid.next);
return node;
}
public ListNode findPreMid(ListNode head) {
ListNode slow = head, fast = head.next, preMid = slow;
while (fast != null && fast.next != null) {
preMid = slow;
slow = slow.next