LeetCode Convert Sorted List to Binary Search Tree

来源:互联网 发布:数据库原理教学大纲 编辑:程序博客网 时间:2024/06/04 18:25

Convert Sorted List to Binary Search Tree


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


Solution:



public class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        if (head == null) return null;
        if (head.next == null) return new TreeNode(head.val);
        
        ListNode headcopy = head;
        ListNode next = head;
        ListNode leftend = head;
        while (next.next.next != null){
            next = next.next.next;
            leftend = headcopy;
            headcopy = headcopy.next;
            if (next.next == null) break;
        }
        ListNode right = headcopy.next;
        leftend.next = null;


        TreeNode root = new TreeNode(headcopy.val);
        if (headcopy != head) root.left = sortedListToBST(head); else root.left = null;
        root.right = sortedListToBST(right);
        return root;
        
    }

0 0
原创粉丝点击