【Leetcode】109. Convert Sorted List to Binary Search Tree

於淼發表於2018-03-01

Question:

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

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

Given the sorted linked list: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

Tips:

給定一個有序的單連結串列,將其轉換成一個平衡二叉查詢樹。

思路:

(1)找到連結串列的中間位置,作為BST的根節點。方法就是設定兩個指標,fast、slow,slow每次走一步,fast每次走兩步。當fast先遇到null,slow就指向連結串列中間節點。

(2)左、右子樹的根節點也用相同的方法找到,並作為根節點的左右子樹。接下來的結點可用遞迴來解決。

程式碼:

public TreeNode sortedListToBST(ListNode head){
        if(head==null) return null;
        return toBST(head,null);
    }

    private TreeNode toBST(ListNode head,ListNode tail) {
        if(head==tail) return null;
        ListNode fast=head;
        ListNode slow=head;
        //迴圈找到連結串列中間位置作為根節點。
        while(fast!=tail && fast.next!=tail){
            slow=slow.next;
            fast=fast.next.next;
        }
        TreeNode root=new TreeNode(slow.val);
        root.left=toBST(head,slow);
        root.right=toBST(slow.next,tail);
        return root;
    }

 

相關文章