LeetCode ---- 109、有序链表转换二叉搜索树

题目链接

思路:

先将单链表的所有节点值存入数组中,由于单链表本身保持升序,那么得到的数组也一定是升序状态,剩下的操作就变成了利用有序数组构造二叉平衡搜索树了

接下来利用这个数组去构造二叉平衡搜索树,每次取数组可选范围内的中间位置为根节点,在其左边为左子树,右边为右子树

递归进行查找添加即可。

    public TreeNode sortedListToBST(ListNode head) {
        if (head == null) {
            return null;
        }
        int len = 0;
        ListNode cur = head;
        // 遍历单链表拿到长度
        while (cur != null) {
            cur = cur.next;
            len++;
        }
        int[] arr = new int[len];
        cur = head;
        // 在数组中填充单链表的值
        for (int i = 0; i < len; i++) {
            arr[i] = cur.val;
            cur = cur.next;
        }
        // 构建二叉平衡搜索树
        return sortedListToBST(arr, 0, arr.length - 1);
    }    
    /**
     * @param arr    当前数组
     * @param start  数组中开始位置
     * @param end    数组中结束位置
     * @return
     **/
    private TreeNode sortedListToBST(int[] arr, int start, int end) {
        if (start > end) {
            return null;
        }
        int mid = (start + end) / 2;
        // 根节点为mid
        TreeNode root = new TreeNode(arr[mid]);
        // [start, mid - 1]为左子树
        root.left = sortedListToBST(arr, start, mid - 1);
        // [mid + 1, end]为右子树
        root.right = sortedListToBST(arr, mid + 1, end);
        return root;
    }
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }
    class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }

猜你喜欢

转载自blog.csdn.net/sinat_34679453/article/details/107570229