109. Convert Sorted List to Binary Search Tree
生活随笔
收集整理的這篇文章主要介紹了
109. Convert Sorted List to Binary Search Tree
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
原始地址:https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/#/description
描述
給定一個按照升序排序的單鏈表,將它轉換成一個高度平衡的二叉搜索樹。
分析
如果要保持二叉搜索樹高度平衡,那么要求插入的順序和二叉樹按層遍歷的順序是一致的,也即每次都找到鏈表的中間節點并插入,并將中間節點的兩側分成兩個子鏈表分別轉換成中間節點的左右子樹,如此遞歸進行。
解法
/*** 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;} }轉載于:https://www.cnblogs.com/fengdianzhang/p/6826770.html
總結
以上是生活随笔為你收集整理的109. Convert Sorted List to Binary Search Tree的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2017/05/07 java 基础
- 下一篇: adb 功能大全