Convert Sorted List to Binary Search Tree

有序链表转平衡二叉搜索树
本文介绍了一种将升序排列的单链表转换为高度平衡的二叉搜索树的方法。通过递归地查找中间节点作为根节点,并以此为基础构建左子树和右子树,最终形成一棵平衡的二叉搜索树。

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.



package Tree;

/**
 * @Title: Convert_Sorted_List_to_Binary_Search_Tree.java
 * @Package Tree
 * @Description: TODO
 * @author nutc
 * @date 2013-9-1 下午2:46:08
 * @version V1.0
 */
public class Convert_Sorted_List_to_Binary_Search_Tree {
	public static void main(String args[]) {
		Convert_Sorted_List_to_Binary_Search_Tree l = new Convert_Sorted_List_to_Binary_Search_Tree();
		l.dos();
	}

	public void dos() {
		ListNode l1 = new ListNode(-1);
		ListNode l2 = new ListNode(0);
		ListNode l3 = new ListNode(1);
		ListNode l4 = new ListNode(2);
		l1.next = l2;
		l2.next = l3;
		l3.next = l4;
		sortedListToBST(l1);
	}

	 public TreeNode sortedListToBST(ListNode head) {
	        if(head ==null) return null;
	        ListNode end = head; 
	        int len = 0;
	        while(end!=null){
	            end= end.next;
	            len++;
	        }
	        
	        return find(head,len);
	    }
	    
	    public TreeNode find(ListNode start,int len){
	        //ListNode pre = null;
	        ListNode p1 =start;
	        //p2 = start;
	        if(start==null||len<=0)
	            return null;
	            
	        int mid = len/2;
	        for(int i=0;i<mid;i++){
	            p1 = p1.next;
	        }
	        /*
	        while(p2!=null && p2!=end){  //
	            pre = p1;
	            p1=p1.next;
	            p2=p2.next.next;
	        }*/
	        TreeNode node = new TreeNode(p1.val);
	        node.left = find(start,mid);
	        node.right = find(p1.next,len-mid-1);
	        return node;
	    }

	public class ListNode {
		int val;
		ListNode next;

		ListNode(int x) {
			val = x;
			next = null;
		}

	}

	public class TreeNode {
		int val;
		TreeNode left;
		TreeNode right;

		TreeNode(int x) {
			val = x;
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值