Convert Sorted List to Binary Search Tree

来源:互联网 发布:淘宝情趣用品货源 编辑:程序博客网 时间:2024/04/29 03:55

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

这道题目相比其他的binary tree 以及linked list 题目要难一些,理解也更抽象一些
一种比较容易想到的方法是每次都用一个 low 一个fast 指针来找重点,这样子需要重复遍历。
更加smart 的方法是下面的实现,用cur 做了一次遍历。 但是比较容易出错。


例如 1,2 ,3,4,5,6,7        //7个listnodes, size 分别表示还需要convert 的有几个值


1:对于1,2 ,3,4,5,6,7 :   (1,2,3)<-----------4---------->(5,6,7
-------------------------------------------       left 剩 3 个(size/2)    根     right 剩 3 个 (size - (size/2 + 1))
    
2:对于1,2,3:           (1)<- 2-> 3
3:对于1:                  (null)  1  (null)

 //此时 1 的左右都为null,即 size 为0,说明 1为leaf,直接返回


cur 开始为1,除了toBST(0), 当size不为0时,每一次BST操作,则cur=cur.next.




/** * 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 {    ListNode cur;    public TreeNode sortedListToBST(ListNode head) {        if (head == null) {            return null;        }        int size = getSize(head);        cur = head;        return toBST(size);            }    private TreeNode toBST(int size) {        if (size <= 0) {            return null;        }        TreeNode leftTreeNode = toBST(size / 2 );        TreeNode root = new TreeNode(cur.val);        cur = cur.next;        TreeNode rightTreeNode = toBST(size - size / 2 - 1);        root.left = leftTreeNode;        root.right = rightTreeNode;        return root;    }    private int getSize(ListNode head) {        if (head == null) {            return 0;        } else {            int count = 0;            while (head != null) {                count ++;                head = head.next;            }            return count;        }    }}


0 0
原创粉丝点击