LeetCode Convert Sorted List to Binary Search Tree 解題報告,leetcodesorted
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
從給定的有序鏈表產生平衡二叉樹。
解題思路:最容易想到的就是利用數組產生二叉樹的方法,找到中間節點作為二叉樹的root節點,然後分別對左右鏈表遞迴調用分別產生左子樹和右子樹。時間複雜度O(N*lgN)
AC代碼:
public class Solution { ListNode getLeftNodeFromList(ListNode head) { ListNode next = head; ListNode current = head; ListNode pre = head; while(next!=null) { next = next.next; if(next==null) { break; } next = next.next; if(next==null) { break; } pre = head; head = head.next; } return pre; } public TreeNode sortedListToBST(ListNode head) { if(head==null) { return null; } if(head.next==null) { return new TreeNode(head.val); } ListNode left = getLeftNodeFromList(head); ListNode mid = left.next; TreeNode root = new TreeNode(mid.val); left.next = null; root.left = sortedListToBST(head); root.right = sortedListToBST(mid.next); return root; }}