【问题描述】[中等]
【解答思路】
1. 分治 快慢指针
复杂度
class Solution {public TreeNode sortedListToBST(ListNode head) {return buildTree(head, null);}public TreeNode buildTree(ListNode left, ListNode right) {if (left == right) {return null;}ListNode mid = getMedian(left, right);TreeNode root = new TreeNode(mid.val);root.left = buildTree(left, mid);root.right = buildTree(mid.next, right);return root;}public ListNode getMedian(ListNode left, ListNode right) {ListNode fast = left;ListNode slow = left;while (fast != right && fast.next != right) {fast = fast.next;fast = fast.next;slow = slow.next;}return slow;}
}
2. 分治 + 中序遍历优化
复杂度
class Solution {ListNode globalHead;public TreeNode sortedListToBST(ListNode head) {globalHead = head;int length = getLength(head);return buildTree(0, length - 1);}public int getLength(ListNode head) {int ret = 0;while (head != null) {++ret;head = head.next;}return ret;}public TreeNode buildTree(int left, int right) {if (left > right) {return null;}int mid = (left + right + 1) / 2;TreeNode root = new TreeNode();root.left = buildTree(left, mid - 1);root.val = globalHead.val;globalHead = globalHead.next;root.right = buildTree(mid + 1, right);return root;}
}
【总结】
1. 前中后序遍历变化的是[中]的位置,左到右的顺序不改变
前序遍历 中左右
中序遍历 左中右
后续遍历 左右中
2.二叉搜索树 关键 找到中位数
3.相关题目
[Leetcode][第108题][JAVA][将有序数组转换为二叉搜索树][二分法][递归]
转载链接:https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree/solution/you-xu-lian-biao-zhuan-huan-er-cha-sou-suo-shu-1-3/