Leetcode-Convert Sorted List to BST.

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

Solution:

 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 TreeNode sortedListToBST(ListNode head) {
20         if (head==null)
21             return null;
22         
23         ListNode end = head;
24         while (end.next!=null){
25             end = end.next;
26         }
27         TreeNode root = sortedListToBSTRecur(head,end);
28         
29         return root;
30     }
31     
32     //Convert the list from head to end into BST, return the root node
33     public TreeNode sortedListToBSTRecur(ListNode head, ListNode end){
34         //If only one node.
35         if (head==end){
36             TreeNode root = new TreeNode(head.val);
37             return root;
38         }
39         
40         //If only two node.
41         if (head.next==end){
42             TreeNode root = new TreeNode(head.val);
43             TreeNode child = new TreeNode(end.val);
44             root.right = child;
45             return root;
46         }
47         
48         
49         //Otherwise, count the number of node in the list, find out the median one, 
50         //and convert the left list and right list to BST.
51         int nodeNum = 1;
52         ListNode curNode = head;
53         while (curNode!=end){
54             curNode = curNode.next;
55             nodeNum++;
56         }
57         int mid = nodeNum/2+nodeNum%2;
58         ListNode median = null;
59         ListNode pre = null;
60         curNode = head;
61         //NOTE: we only need to move (mid-1) steps to move curNode to the median one.
62         for (int i=0;i<mid-1;i++){
63             pre = curNode;
64             curNode = curNode.next;
65         }
66         median = curNode;
67         TreeNode root = new TreeNode(median.val);
68         TreeNode leftChild = sortedListToBSTRecur(head,pre);
69         TreeNode rightChild = sortedListToBSTRecur(median.next,end);
70         root.left = leftChild;
71         root.right = rightChild;
72         return root;
73     }
74 }

For a list from head to end, we find out the median node and use recursion method to convert its left list and right list to BST, and then connect the left subtree and right subtree to the median node.

转载于:https://www.cnblogs.com/lishiblog/p/4084303.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值