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

有序链表变成二叉搜索树

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;
    }
}
全部评论

相关推荐

牛客383479252号:9,2学生暑期实习失利开始投小厂,给这群人整自信了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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