码迷,mamicode.com
首页 > 编程语言 > 详细

排序列表转换为二分查找树

时间:2016-07-12 10:33:23      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:

题目

给出一个所有元素以升序排序的单链表,将它转换成一棵高度平衡的二分查找树

解题

找到中间点,建立树的根结点
左右半边递归
注意:
右半边链表可以根据找到的中间节点进行递归
左半边要找到结束位置,这里我新建了一个链表

/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The first node of linked list.
     * @return: a tree node
     */

    public TreeNode sortedListToBST(ListNode head) {  
        // write your code here
        ListNode p1 = head;
        ListNode mid = findMiddle(p1);
        if(mid==null)
            return null;
        TreeNode root = new TreeNode(mid.val);
        // 右边递归
        TreeNode right = sortedListToBST(mid.next);

        if(right!=null)
            root.right = right;
        // 找到left半边
        ListNode leftHead = new ListNode(-1);
        ListNode leftList = leftHead;
        while(head!=null && head!=mid){
            leftList.next = head;
            leftList = leftList.next;
            head = head.next;
        }
        leftList.next = null;
        // 左边递归
        TreeNode left = sortedListToBST(leftHead.next);
        if(left!=null)
            root.left = left;

        return root;
    }
    // 找到中间节点
    public ListNode findMiddle(ListNode head){
        if(head==null || head.next==null){
            return head;
        }
        ListNode slow = head;
        ListNode fast = head;
        while(fast!=null && fast.next!=null && fast.next.next!=null){
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }


}

排序列表转换为二分查找树

标签:

原文地址:http://blog.csdn.net/qunxingvip/article/details/51886364

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