Convert Sorted List to Binary Search Tree

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

SOLUTION 2:

Java不能使用指针，所以我们自建一个自定义的类，里面只有一个ListNode，这样我们就能方便地修改入参了（好纠结啊，这时主页君就开始怀念起C的指针了）,
:)
C++版本可以参见张磊哥哥的解答喔：）
1 public TreeNode sortedListToBST(ListNode head) {
2         if (head == null) {
3             return null;
4         }
5
6         int size = 0;
8         while (cur != null) {
9             size++;
10             cur = cur.next;
11         }
12
13         CurrNode curNode = new CurrNode(head);
14         return sortedListToBSTHelp(curNode, size);
15     }
16
17     public class CurrNode {
18         ListNode node;
19
20         CurrNode(ListNode node) {
21             this.node = node;
22         }
23     }
24
25     // when the recursion is done, the curr node should point to the node
26     // which is the next of the block.
27     public TreeNode sortedListToBSTHelp(CurrNode curr, int size) {
28         if (size <= 0) {
29             return null;
30         }
31
32         TreeNode left = sortedListToBSTHelp(curr, size/2);
33
34         // because we want to deal with the right block.
35         TreeNode root = new TreeNode(curr.node.val);
36         curr.node = curr.node.next;
37
38         TreeNode right = sortedListToBSTHelp(curr, size - 1 - size/2);
39
40         root.left = left;
41         root.right = right;
42
43         return root;
44     }
View Code

SOLUTION 3:

root.left = left;
root.right = right;
return root;
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     ListNode curNode = null;
20
21     public TreeNode sortedListToBST(ListNode head) {
22         if (head == null) {
23             return null;
24         }
25
26         int size = 0;
28         while (cur != null) {
29             size++;
30             cur = cur.next;
31         }
32
35     }
36
37     // Use the size to control.
38     public TreeNode dfs(ListNode head, int size) {
39         if (size <= 0) {
40             return null;
41         }
42
43         TreeNode left = dfs(head, size / 2);
44         TreeNode root = new TreeNode(curNode.val);
45
46         // move the current node to the next place.
47         curNode = curNode.next;
48         TreeNode right = dfs(curNode, size - size / 2 - 1);
49
50         root.left = left;
51         root.right = right;
52
53         return root;
54     }
55 }
View Code

posted on 2015-04-04 13:48  Yu's Garden  阅读(1595)  评论(0编辑  收藏