Convert Sorted List to Binary Search Tree

来源:互联网 发布:云计算产业的盈利模式 编辑:程序博客网 时间:2024/06/06 00:33

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

public TreeNode sortedListToBST(ListNode head) {            // base case            if (head == null) return null;            ListNode slow = head;            ListNode fast = head;            ListNode prev = null;            // find the median node in the linked list, after executing this loop            // fast will pointing to the last node, while slow is the median node.            while (fast.next != null) {                fast = fast.next;                if (fast.next == null) {                    break;                }                fast = fast.next;                prev = slow;                slow = slow.next;            }            if (prev != null) prev.next = null;            else head = null;            TreeNode root = new TreeNode(slow.val);            root.left = sortedListToBST(head);            root.right = sortedListToBST(slow.next);            return root;        }


public TreeNode sortedListToBST(ListNode head) {    if(head == null){        return null;    }    int size = 0;    ListNode runner = head;    node = head;    while(runner != null){        runner = runner.next;        size ++;    }    return inorderHelper(0, size - 1);}public TreeNode inorderHelper(int start, int end){    if(start > end){        return null;    }    int mid = start + (end - start) / 2;    TreeNode left = inorderHelper(start, mid - 1);    TreeNode treenode = new TreeNode(node.val);    treenode.left = left;    node = node.next;    TreeNode right = inorderHelper(mid + 1, end);    treenode.right = right;    return treenode;}


0 0
原创粉丝点击