【LeetCode-面试算法经典-Java实现】【109-Convert Sorted List to Binary Search Tree(排序链表转换成二叉排序树)】...
生活随笔
收集整理的這篇文章主要介紹了
【LeetCode-面试算法经典-Java实现】【109-Convert Sorted List to Binary Search Tree(排序链表转换成二叉排序树)】...
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【109-Convert Sorted List to Binary Search Tree(排序鏈表轉換成二叉排序樹)】
【LeetCode-面試算法經典-Java實現】【全部題目文件夾索引】
原題
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
題目大意
給定一個升序的單鏈表。將它轉換成一顆高度平衡的二叉樹
解題思路
解法一:將單鏈表中的值存入一個數組中,通過數組來構建二叉樹。算法時間復雜度是:O(n),空間復雜度是:O(n)
解法二:採用遞歸的方式。
(一)找中間結點,構建根結點。
(二)中間結點左半部分構建左子樹,
(三)中間結點的右部分構建右子樹
題採用另外一種解法
代碼實現
樹結點類
public class TreeNode {int val;TreeNode left;TreeNode right;TreeNode(int x) { val = x; } }算法實現類
public class Solution {public TreeNode sortedListToBST(ListNode head) {// 假設鏈表為空就直接返回nullif (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;} }評測結果
點擊圖片,鼠標不釋放。拖動一段位置。釋放后在新的窗體中查看完整圖片。
特別說明
歡迎轉載,轉載請注明出處【http://blog.csdn.net/derrantcm/article/details/47393027】
總結
以上是生活随笔為你收集整理的【LeetCode-面试算法经典-Java实现】【109-Convert Sorted List to Binary Search Tree(排序链表转换成二叉排序树)】...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Why Did the Cow Cros
- 下一篇: iOS 开发 OpenGL 新手入门