日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

109. Convert Sorted List to Binary Search Tree

發布時間:2025/7/14 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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) {} }

描述

給定一個按照升序排序的單鏈表,將它轉換成一個高度平衡的二叉搜索樹。

分析

如果要保持二叉搜索樹高度平衡,那么要求插入的順序和二叉樹按層遍歷的順序是一致的,也即每次都找到鏈表的中間節點并插入,并將中間節點的兩側分成兩個子鏈表分別轉換成中間節點的左右子樹,如此遞歸進行。

解法

/*** 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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。