日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

109. Convert Sorted List to Binary Search Tree

發(fā)布時(shí)間:2025/7/14 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 109. Convert Sorted List to Binary Search Tree 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

題目

原始地址: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) {} }

描述

給定一個(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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。