ITeye博客

Convert Sorted List to Binary Search Tree

KickCode · 2016-02-08 05:30 · Leetcode · 编程语言 · Markdown

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

给定一个单向有序的列表,将它转换成一颗平衡二叉搜索树。我们采用快慢指针,然后确定链表中的中间节点,将中间作为当前子树的根节点,然后将链表分为两段,递归完成。代码如下:


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        if(head == null) return null;
        ListNode fast = head;
        ListNode slow = head;
        ListNode pre = null;
        while(fast != null && fast.next != null) {
            pre = slow;
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode rightHead = slow.next;
        TreeNode root = new TreeNode(slow.val);
        if(pre != null) {
            pre.next = null;
            root.left = sortedListToBST(head);
        }
        root.right = sortedListToBST(rightHead);
        return root;
    }
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。