zl程序教程

您现在的位置是:首页 >  后端

当前栏目

LeetCode109_Convert Sorted List to Binary Search t题目tiTree(将链表转成二叉排序树) Java题解

JAVAList链表排序 to 题解 题目 search
2023-09-27 14:25:17 时间
题目:

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

题解:将一个有序链表转成二叉排序树,假设是一棵相对平衡的排序树,应该是这种,链表中间那个节点为树的根节点。根节点的左子树节点应该是根节点左边那部分的中间节点,根节点的右节点应该是根节点右边那部分链表的中间节点,后面就依照这个规律依次类推了。

知道上面的规律之后,问题的关键点就是寻找一个链表的中间节点了,这个应该是非常熟悉的。用快慢两个指针能够轻松解决。

以下是这种思路的实现代码:

代码:

//相似归并排序 O(Nlogn)
   public static TreeNode sortedListToBST(ListNode head) {
	   ListNode fast=head;
	   ListNode slow=head;
	   
	   if(head==null)//递归结束条件
		   return null;
	   
	   ListNode leftOfMid=null;//用来记录中间节点的前一个节点。这里把slow指向的节点看做中间及诶单
	   while(fast.next!=null&&fast.next.next!=null)
	   {
		   fast=fast.next.next;
		   leftOfMid=slow;
		   slow=slow.next;
	   }
	   
	   if(leftOfMid==null)//说明没有进入上面的while循环 说明这时候仅仅有1个或两个节点  这时候就不存在左链表的左半部分了
		   head=null;
	   else 
		   leftOfMid.next=null;//假设有左半部分则把左半部分链表的末尾指向空,将链表截两段
	
	   ListNode rightOfMid=slow.next;//链表右半部分的開始
	 
	   TreeNode root=new TreeNode(slow.val);
	   root.left=sortedListToBST(head);
	   root.right=sortedListToBST(rightOfMid);
	   return root;
	   
        
    }
上面的时间复杂区是n*logn,有没有O(n)的算法呢,新建每个树节点一遍下来时间复杂度就是o(n)了,所以在寻找中间节点的时候仅仅能是常数时间,这样才干让终于的时间复杂度为O(n),这样仅仅能借助哈希表进行辅助了

代码:

 //用哈希表O(n)时间复杂度
   public static TreeNode sortedListToBST2(ListNode head) {
	   Hashtable< Integer, TreeNode> hashtable=new Hashtable<>();
	   if(head==null)
		   return null;
	   ListNode cur=head;
	   int length=0;
	   while(cur!=null)
	   {
		  
		   TreeNode node=new TreeNode(cur.val);
		   hashtable.put(length,node );
		   cur=cur.next;
		   length++;
	   }
	   
	   return buildTree(0, length-1, hashtable);
	   
   }
   
   public static TreeNode buildTree(int start,int end,Hashtable<Integer, TreeNode> hashtable) {
	   if(start<=end)
	   {
		   int mid=(start+end)/2;
		   TreeNode root=hashtable.get(mid);
		   root.left=buildTree(start,mid-1 , hashtable);
		   root.right=buildTree(mid+1, end, hashtable);
		   return root;
	   }
	   else {
		return null;
	}
	   
	   
	
}