您的位置:首页 > 其它

*LeetCode-Convert Sorted List to Binary Search Tree

2015-09-28 23:03 204 查看
inorder就是顺序的一个linked list

每次找到list的中间 就是root 左边sub list中间就是左子 右边sub list的中间就是右子

但是注意只有一个node的情况 要把head设置成null 而且每次找到mid之后  要把mid之前的那个node.next = null 

o(nlogn)

public class Solution {
public TreeNode sortedListToBST(ListNode head) {
if ( head == null )
return null;
ListNode fast = head;
ListNode slow = head;
ListNode pre = null;
while ( fast != null && fast.next != null ){
fast = fast.next.next;
pre = slow;
slow = slow.next;
}
if ( pre != null )
pre.next = null;
else
head = null;
TreeNode root = new TreeNode ( slow.val );
root.left = sortedListToBST(head);
root.right = sortedListToBST(slow.next);
return root;
}
}
o(n)做法
The method 1 constructs the tree from root to leaves. In this method, we construct from leaves to root. The idea is to insert nodes in BST in the same order as the appear in Linked List, so that the tree can be constructed in
O(n) time complexity. We first count the number of nodes in the given Linked List. Let the count be n. After counting nodes, we take left n/2 nodes and recursively construct the left subtree. After left subtree is constructed, we allocate memory for root and
link the left subtree with root. Finally, we recursively construct the right subtree and link it with root.
While constructing the BST, we also keep moving the list head pointer to next so that we have the appropriate pointer in each recursive call.
从list头开始 用一个全局指针来当pointer 每次建好左树 建一个rootnode pointer ++ 然后建右树 

每个node访问一遍 就是inorder的顺序 bottom up做的

public class Solution {
private ListNode node;
public TreeNode sortedListToBST(ListNode head) {
if ( head == null )
return null;
ListNode pt = head;
node = head;
int count = 0;
while ( head != null ){
head = head.next;
count ++;
}
return helper ( 0, count - 1 );
}
public TreeNode helper ( int start, int end ){
if ( start > end )
return null;
int mid = start + ( end - start ) / 2;
TreeNode left = helper ( start, mid - 1 );
TreeNode root = new TreeNode ( node.val );
root.left = left;
node = node.next;
root.right = helper ( mid + 1, end );
return root;
}


helper里面的start end只是用来计数的 我觉得 为了判断停止条件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: