Convert Sorted Array to Binary Search Tree
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def disp(self):
print self.val
if(self.left!=None):
self.left.disp()
if(self.right!=None):
self.right.disp()
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param head, a list node
# @return a tree node
def sortedListToBST(self, head):
l=[]
while(head!=None):
l.append(head.val)
head=head.next
#print l
return self.sortArray2BST(l)
def sortArray2BST(self,arr):
if(len(arr)==0):
return None
if(len(arr)==1):
return TreeNode(arr[0])
else:
mid=len(arr)/2
treenode=TreeNode(arr[mid])
treenode.left=self.sortArray2BST(arr[0:mid])
treenode.right=self.sortArray2BST(arr[mid+1:len(arr)])
return treenode
将linked-list转化为array,有别人提出的不转化的办法是通过两个指针,第一个指针每次走一位,第二个指针每次走两位,第二个指针走到最后的时候,第一个指针走到中间位。
可用多个指针(速度不同)进行对链表的定位