Convert Sorted List to Binary Search Tree

本文介绍如何将一个排序好的单链表转换为平衡的二叉搜索树,通过从链表中逐个取出节点并构建树的方式实现。详细解释了两种解决方案:一种是传统的自顶向下的方法,另一种是创新的自底向上的方法,后者避免了查找中间节点的复杂度,简化了过程。

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

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

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; next = null; }
 7  * }
 8  */
 9 /**
10  * Definition for binary tree
11  * public class TreeNode {
12  *     int val;
13  *     TreeNode left;
14  *     TreeNode right;
15  *     TreeNode(int x) { val = x; }
16  * }
17  */
18 public class Solution {
19 public class TreeNodes{
20         TreeNode r;
21         TreeNode get(){return r;}
22         void set(int i){this.r.val = i;}
23         TreeNodes(){}
24         TreeNodes(TreeNode rr){this.r = rr;}
25     }
26     public TreeNodes root;
27     public TreeNode sortedListToBST(ListNode head) {
28         // Start typing your Java solution below
29         // DO NOT write main() function
30         ListNode temp = head;
31         root = new TreeNodes(new TreeNode(0));
32         int length = 0;
33         while(temp!=null){
34             temp=temp.next;
35             length++;
36         }
37         if(length == 0)return null;
38         toBST(head,0,length-1,root);
39         return root.get();
40     }
41     
42     
43     public TreeNode toBST(ListNode head, int start, int end,TreeNodes r){
44         if(start>end) return null;
45         
46         int mid=(start+end)/2;
47         ListNode tmp = head;
48         for(int i = 0; i < mid; i ++){
49             tmp = tmp.next;
50         }
51         r.set(tmp.val);
52         r.get().left = toBST(head, start,mid-1,new TreeNodes(new TreeNode(0))); 
53         r.get().right = toBST(head, mid+1,end,new TreeNodes(new TreeNode(0)));
54         return r.get();
55     }
56 }

 


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


If you have not checked out my previous post: Convert Sorted Array to Balanced Binary Search Tree (BST), you should check it out now as this solution is built upon the previous solution.

Things get a little more complicated when you have a singly linked list instead of an array. Please note that in linked list, you no longer have random access to an element in O(1) time.

Singly-linked lists contain nodes which have a data field as well as a  next field, which points to the next node in the linked list.

Naive Solution:
A naive way is to apply the previous solution directly. In each recursive call, you would have to traverse half of the list’s length to find the middle element. The run time complexity is clearly O(N lg N), where N is the total number of elements in the list. This is because each level of recursive call requires a total of N/2 traversal steps in the list, and there are a total of lg N number of levels (ie, the height of the balanced tree).

Hint:
How about inserting nodes following the list’s order? If we can achieve this, we no longer need to find the middle element, as we are able to traverse the list while inserting nodes to the tree.

Best Solution:
As usual, the best solution requires you to think from another perspective. In other words, we no longer create nodes in the tree using the top-down approach. We create nodes bottom-up, and assign them to its parents. The bottom-up approach enables us to access the list in its order while creating nodes.

Isn’t the bottom-up approach neat? Each time you are stucked with the top-down approach, give bottom-up a try. Although bottom-up approach is not the most natural way we think, it is extremely helpful in some cases. However, you should prefer top-down instead of bottom-up in general, since the latter is more difficult to verify in correctness.

Below is the code for converting a singly linked list to a balanced BST. Please note that the algorithm requires the list’s length to be passed in as the function’s parameters. The list’s length could be found in O(N) time by traversing the entire list’s once. The recursive calls traverse the list and create tree’s nodes by the list’s order, which also takes O(N) time. Therefore, the overall run time complexity is still O(N).

 

转载于:https://www.cnblogs.com/reynold-lei/p/3316888.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值