LC.P109[有序链表转换二叉搜索树]
方法一:DFS
由于构造出的二叉搜索树的中序遍历结果就是链表本身,因此可以一边对链表遍历,一边对二叉树进行中序遍历。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
class Solution { ListNode head;
public TreeNode sortedListToBST(ListNode head) { this.head = head; int n = 0; ListNode p = head; while (p != null) { p = p.next; ++n; } return build(0, n -1); }
private TreeNode build(int left, int right) { if (left > right) return null; int mid = left + right >> 1; TreeNode node = new TreeNode(); node.left = build(left, mid - 1); node.val = head.val; head = head.next; node.right = build(mid + 1, right); return node; } }
|
- 时间复杂度:$O(n)$
- 空间复杂度:$O(logn)$