leetcode 109. Convert Sorted List to Binary Search Tree
Posted hwd9654
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 109. Convert Sorted List to Binary Search Tree相关的知识,希望对你有一定的参考价值。
其实就是一个二分搜索
首先遍历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的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 109. Convert Sorted List to Binary Search Tree
Leetcode109. Convert Sorted List to Binary Search Tree
LeetCode-109-Convert Sorted List to Binary Search Tree
leetcode109. Convert Sorted List to Binary Search Tree