首页 > 其他 > 详细

Convert Sorted List to Binary Search Tree

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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!