109. Convert Sorted List to Binary Search Tree
生活随笔
收集整理的這篇文章主要介紹了
109. Convert Sorted List to Binary Search Tree
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目
原始地址:https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/#/description
描述
給定一個(gè)按照升序排序的單鏈表,將它轉(zhuǎn)換成一個(gè)高度平衡的二叉搜索樹。
分析
如果要保持二叉搜索樹高度平衡,那么要求插入的順序和二叉樹按層遍歷的順序是一致的,也即每次都找到鏈表的中間節(jié)點(diǎn)并插入,并將中間節(jié)點(diǎn)的兩側(cè)分成兩個(gè)子鏈表分別轉(zhuǎn)換成中間節(jié)點(diǎn)的左右子樹,如此遞歸進(jìn)行。
解法
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/ /*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/ public class Solution {public TreeNode sortedListToBST(ListNode head) {return insertNode(head, null);}private TreeNode insertNode(ListNode head, ListNode tail) {if (head == null || head == tail) {return null;}ListNode fast = head, slow = head;while (fast != tail && fast.next != tail) {fast = fast.next.next;slow = slow.next;}TreeNode root = new TreeNode(slow.val);root.left = insertNode(head, slow);root.right = insertNode(slow.next, tail);return root;} }轉(zhuǎn)載于:https://www.cnblogs.com/fengdianzhang/p/6826770.html
總結(jié)
以上是生活随笔為你收集整理的109. Convert Sorted List to Binary Search Tree的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2017/05/07 java 基础
- 下一篇: adb 功能大全