LeetCode------Convert Sorted List to Balanced Binary Search Tree

LeetCode------Convert Sorted List to Balanced Binary Search Tree_第1张图片

要求把有序链表转为二叉搜索树,和之前那道Convert Sorted Array to Binary Search Tree 将有序数组转为二叉搜索树思路完全一样,只不过是操作的数据类型有所差别,一个是数组,一个是链表。数组方便就方便在可以通过index直接访问任意一个元素,而链表不行。由于二分查找法每次需要找到中点,而链表的查找中间点可以通过快慢指针来操作,找到中点后,要以中点的值建立一个数的根节点,然后需要把原链表断开,分为前后两个链表,都不能包含原中节点,然后再分别对这两个链表递归调用原函数,分别连上左右子节点即可。


实例代码:

package com.zhumq.lianxi;

public class ConvertSortedListtoBalancedBinarySearchTree {
    //定义TreeNode
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { 
            val = x; 
        }
    }
    //定义ListNode
    public static class ListNode{
        int val;
        ListNode next;
        ListNode(int x) { 
            val = x; 
        }
    }

    public TreeNode sortedListToBST(ListNode head) {
        if (head == null) return null;
        if (head.next == null) return new TreeNode(head.val);
        ListNode slow = head;
        ListNode fast = head;
        ListNode last = slow;
        //last记录末尾指针
        while (fast.next != null  && fast.next.next != null) {
            last = slow;
            slow = slow.next;
            fast = fast.next.next;
        }
        //slow指向的下一个元素为右边的头元素
        fast = slow.next;
        //然后让末尾指针指向空
        last.next = null;
        TreeNode cur = new TreeNode(slow.val);
        if (head != slow) { 
            //分成左右两个子问题
            cur.left = sortedListToBST(head);
            cur.right = sortedListToBST(fast);
        }
        return cur;
    }
}

你可能感兴趣的:(LeetCode)