Leetcode: Convert Sorted List to Binary Search Tree

来源:互联网 发布:网络视频直播软件 编辑:程序博客网 时间:2024/05/18 03:23

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

最直接的思维是list赋值给array,O(n).

以下为bottom-up递归

/** * 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 ListNode cur;public TreeNode sortedListToBST(ListNode head) {// Start typing your Java solution below// DO NOT write main() functionif(head == null)return null;int size = 1;ListNode ptr = head;this.cur = head;while(ptr.next != null){ptr = ptr.next;size++;}return convert(0, size - 1);}public TreeNode convert(int start, int end){if(start > end)return null;int mid = start + (end - start) / 2;TreeNode left = convert(start, mid - 1);TreeNode parent = new TreeNode(cur.val);parent.left = left;cur = cur.next;parent.right = convert(mid + 1, end);return parent;}}


原创粉丝点击