ConvertSortedListToBinarySearchTree

来源:互联网 发布:dnf端口辅助怎么稳定 编辑:程序博客网 时间:2024/06/03 17:51
1.问题描述
根据给定的有序单链表,创建一个平衡二叉查找树(每个节点node的左子树node.left上的节点值都小于node.val,每个节点node的右子树node.right上的节点值都大于node.val)
2.解题思路
寻找head(开始节点),tail(结束节点)的中位节点,即采用fast指针和slow指针完成,其中fast指针遍历的速度是slow指针的两倍,这样每次遍历完slow指针所表示的节点即为此时的根节点
3.程序源码
public TreeNode sortedListToBST(ListNode head) {
        return toBST(head, null);
    }




    private TreeNode toBST(ListNode head, ListNode tail) {
        if (head == tail)
            return null;
        // 申请两个指针,fast移动速度是low的两倍
        ListNode fast = head;
        ListNode slow = head;
        while (fast != tail && fast.next != tail) {
            fast = fast.next.next;
            slow = slow.next;
        }
        TreeNode root = new TreeNode(slow.val);
        root.left = toBST(head, slow);
        root.right = toBST(slow.next, tail);




        return root;
    }