Convert Sorted List to Binary Search Tree

来源:互联网 发布:python基础编程第二版 编辑:程序博客网 时间:2024/06/05 17:25

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; next = null; } * } *//** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public TreeNode sortedListToBST(ListNode head) {        return constructBST(head);    }    public TreeNode constructBST(ListNode head){        if(head==null) return null;        if(head.next==null) return new TreeNode(head.val);        ListNode fast=head;        ListNode slow=head;        ListNode prev=null;        while(fast!=null && fast.next!=null){            fast=fast.next.next;            prev=slow;            slow=slow.next;        }        if(prev!=null) prev.next=null;        TreeNode tree=new TreeNode(slow.val);        tree.left=constructBST(head);        tree.right=constructBST(slow.next);        return tree;    }}


0 0
原创粉丝点击