将有序表转化为二叉搜索树

来源:互联网 发布:提醒软件 编辑:程序博客网 时间:2024/04/23 16:37

题目描述

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) {        if(head==null)return null;        if(head.next==null)return new TreeNode(head.val);        ListNode mid=head,end=head,premid=null;        while(end!=null&&end.next!=null){            premid=mid;            mid=mid.next;            end=end.next.next;        }        premid.next=null;        TreeNode root=new TreeNode(mid.val);        root.left=sortedListToBST(head);        root.right=sortedListToBST(mid.next);        return root;    }}
0 0
原创粉丝点击