标签:class obs image vat width 递归 图片 next private
其实就是一个二分搜索
首先遍历LinkedList,记下链表长度
然后从mid开始,
mid.left = 左部的mid
mid.right = 右部的mid
依次递归,因为这相当于一个中序遍历,调用栈的最底层是从LinkedList首个元素开始的
class Solution { ListNode tmp; public TreeNode sortedListToBST(ListNode head) { tmp = head; ListNode traverse = head; int size = 0; while(traverse != null){ size++; traverse = traverse.next; } return helper(0, size-1); } private TreeNode helper(int start, int end){ if(start > end) return null; int mid = start + (end - start) / 2; TreeNode left = helper(start, mid - 1); TreeNode cur = new TreeNode(tmp.val); cur.left = left; tmp = tmp.next; TreeNode right = helper(mid+1, end); cur.right = right; return cur; } }
leetcode 109. Convert Sorted List to Binary Search Tree
标签:class obs image vat width 递归 图片 next private
原文地址:https://www.cnblogs.com/hwd9654/p/11371360.html