我是将链表转成了数组,然后就变成和108题是一样的了。
但是效果并不是很好。
public TreeNode sortedListToBST(ListNode head) { ArrayList<Integer> list = new ArrayList<>(); if(head == null) { return null; } while(head != null){ list.add(head.val); head = head.next; } int[] a = list.stream().mapToInt(Integer::valueOf).toArray(); return sortedArrayToBST(a,0,a.length-1); } private TreeNode sortedArrayToBST(int[] nums, int start, int end) { int n = end - start + 1; if(n == 0){ return null; } int i = n/2; TreeNode node = new TreeNode(nums[start +i]); node.left = sortedArrayToBST(nums,start,start +i-1); node.right = sortedArrayToBST(nums,start + i + 1,end); return node; }
第二种方法,用快慢两个指针找到中间结点的位置,然后进行二叉树的构建;
public TreeNode sortedListToBST(ListNode head) { if(head == null){ return null; } ListNode mid = this.findMiddleElement(head); TreeNode node = new TreeNode(mid.val); if(head == mid){ return node; } node.left = this.sortedListToBST(head); node.right = this.sortedListToBST(mid.next); return node; } private ListNode findMiddleElement(ListNode head) { ListNode prevPtr = null; ListNode slowPtr = head; ListNode fastPtr = head; while(fastPtr != null && fastPtr.next != null){ prevPtr = slowPtr; slowPtr = slowPtr.next; fastPtr = fastPtr.next.next; } if(prevPtr != null){ prevPtr.next = null; } return slowPtr; }
方法三
public TreeNode sortedListToBST(ListNode head) { int size = this.findSize(head); this.head = head; return convertListToBST(0,size - 1); } private TreeNode convertListToBST(int l, int r) { if(l>r){ return null; } int mid = (l+r) / 2; TreeNode left = this.convertListToBST(l,mid - 1); TreeNode node = new TreeNode(this.head.val); node.left = left; this.head = this.head.next; node.right = this.convertListToBST(mid +1,r); return node; } private ListNode head; private int findSize(ListNode head) { //得到链表的长度 ListNode ptr = head; int c = 0; while(ptr != null){ ptr = ptr.next; c += 1; } return c; }
中序遍历。
——2020.7.2