Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.算法
給定一個升序的單鏈表,將它轉換成一顆高度平衡的二叉樹數組
解法一:將單鏈表中的值存入一個數組中,經過數組來構建二叉樹,算法時間複雜度是:O(n),空間複雜度是:O(n)
解法二:採用遞歸的方式,
(一)找中間結點,構建根結點,
(二)中間結點左半部分構建左子樹,
(三)中間結點的右部分構建右子樹
題採用第二種解法 spa
樹結點類.net
public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }
算法實現類code
public class Solution { public TreeNode sortedListToBST(ListNode head) { // 若是鏈表爲空就直接返回null if (head == null) { return null; } // 鏈表只有一個結點 if (head.next == null) { return new TreeNode(head.val); } // 快速移動結點,每次移動兩個位置 ListNode fast = head.next.next; // 記錄中間結點 ListNode mid = head; // 找中間結點 while (fast != null && fast.next != null) { mid = mid.next; fast = fast.next.next; } // 以中間結點的下一個結點做爲根結點 TreeNode root = new TreeNode(mid.next.val); // 構建右子樹 root.right = sortedListToBST(mid.next.next); // 記錄鏈表要斷開的點 ListNode midNext = mid.next; // 斷開單鏈表(會破壞原來單鏈表的結構) mid.next = null; // 構建左子樹 root.left = sortedListToBST(head); // 從新將鏈表接好 mid.next = midNext; // 返回結果 return root; } }