Convert Sorted List to Binary Search Tree leetcode java

本文介绍了一种通过二分法将排序链表转换为高度平衡二叉搜索树的方法,详细解释了从链表到树的构建过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

 

题解

之前做过一道是从sorted array转换到BinarySearchTree的,方法还是一样二分法。但是构造树的方法不是由顶至下了,是要由低至上的建立。

代码如下:

 

 1     static ListNode h;
 2  
 3     public TreeNode sortedListToBST(ListNode head) {
 4         if (head == null)
 5             return null;
 6             
 7         h = head;
 8         
 9         int len = 0;
10         ListNode temp = head;
11         while(temp != null){
12             len++;
13             temp = temp.next;
14         }   
15         return sortedListToBST(0, len - 1);
16     }
17  
18     public TreeNode sortedListToBST(int start, int end) {
19         if (start > end)
20             return null;
21         int mid = (start + end) / 2;
22         TreeNode left = sortedListToBST(start, mid - 1);
23         TreeNode root = new TreeNode(h.val);
24         root.left = left;
25         h = h.next;
26         TreeNode right = sortedListToBST(mid + 1, end);
27         root.right = right;
28  
29         return root;
30     }

 

Reference: http://www.programcreek.com/2013/01/leetcode-convert-sorted-list-to-binary-search-tree-java/

转载于:https://www.cnblogs.com/springfor/p/3884031.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值