题解 | #有序链表变成二叉搜索树#

有序链表变成二叉搜索树

http://www.nowcoder.com/practice/86343165c18a4069ab0ab30c32b1afd0

其实(fast!=null&&fast.next!=null)之前一直写成了(fast.next!=null&&fast.next.next!=null),结果就不对了。

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */
/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @return TreeNode类
     */
    public TreeNode sortedListToBST (ListNode head) {
        // write code here
        if(head==null)
            return null;

        if(head.next==null)
            return new TreeNode(head.val);

        ListNode slow = head;
        ListNode fast = head;
        ListNode preMid = null;

        while(fast!=null&&fast.next!=null){
            preMid = slow;
            slow = slow.next;
            fast = fast.next.next;
        }

        TreeNode root = new TreeNode(slow.val);
        preMid.next = null;
        root.left = sortedListToBST(head);
        root.right = sortedListToBST(slow.next);

        return root;
    }
}
全部评论

相关推荐

07-11 11:10
门头沟学院 Java
请问各位大三兄弟们跟hr说多久实习时间到时候可以提前跑路吗?
程序员小白条:问就是六个月以上,可以一年,实习都这样,你入职后想跑就跑
点赞 评论 收藏
分享
陈逸轩1205:才105 哥们在养生呢
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务