Convert Sorted List to Balanced BST

本文介绍了一种将有序链表转换为高度平衡的二叉搜索树的方法。通过递归方式寻找链表中点作为根节点,并将链表一分为二,分别构建左右子树。

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

Example

               2
1->2->3  =>   / \
             1   3

分析:
非常简单,用递归即可。需要注意返回mid node的时候,要把整个list分成两半。

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 /**
10  * Definition for a binary tree node.
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 TreeNode sortedListToBST(ListNode head) {
20         if (head == null) return null;
21         ListNode mid = middle(head);
22         TreeNode root = new TreeNode(mid.val);
23         root.right = sortedListToBST(mid.next);
24         if (mid != head) {
25             root.left = sortedListToBST(head);
26         }
27         return root;
28     }
29     
30     private ListNode middle(ListNode head) {
31         if (head == null || head.next == null) return head;
32         ListNode pre = null, slow = head, quick = head;
33         
34         while(quick.next != null && quick.next.next != null) {
35             pre = slow;
36             slow = slow.next;
37             quick = quick.next.next;
38         }
39         
40         if (pre != null) {
41             pre.next = null;  // cut the list into halves.
42         }
43         return slow;
44     }
45 }

 

转载于:https://www.cnblogs.com/beiyeqingteng/p/5636498.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值