码迷,mamicode.com
首页 > 其他好文 > 详细

Convert Sorted List to Binary Search Tree

时间:2014-12-30 17:11:39      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:list   bst   递归   

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

将增序链表转换为均衡的二叉查找树 与数组转换相同 找到链表的中间结点 作为树的根节点进行赋值  再将链表以中间节点为界 分为左右子链表 进行递归赋值 代码如下:

public class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        if(head==null)return null;
		ListNode nhead=new ListNode(0);
		nhead.next=head;
		ListNode pre=nhead;
		ListNode slow=head;
		ListNode fast=head;
		while(fast.next!=null&&fast.next.next!=null){
			pre=pre.next;
			slow=slow.next;
			fast=fast.next.next;
		}
		ListNode right=slow.next;
		pre.next=null;
		ListNode left=nhead.next;
		TreeNode root=new TreeNode(slow.val);
		root.left=sortedListToBST(left);
		root.right=sortedListToBST(right);
		return root;
    }
}


Convert Sorted List to Binary Search Tree

标签:list   bst   递归   

原文地址:http://blog.csdn.net/u012734829/article/details/42267303

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!