Leetcode Convert Sorted List to Binary Search Tree 把有序鏈表轉換成二叉搜索樹


題目:


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


分析:

舉一個例子, 假如鏈表爲 1--> 2 --> 3 --> 4 --> 5 --> 6 --> 7。 根據二叉搜索樹的性質 root.val > left.val && root.val < right.val, 轉換成二叉搜索樹應該是

  4

        /    \

      2       6

   /     \    /    \

 1      3  5     7

從這個例子可以看出,鏈表的中間節點是樹的根節點,中間節點把鏈表分成左右兩部分,左右兩個鏈表的中點又分別是根節點左右子樹的根節點。因此,最容易想到用遞歸的方法。

1. 遞歸的結束條件是當節點爲空或節點的next爲空。節點爲空則返回空,節點的next爲空則返回該節點對應的樹節點。

2. 找鏈表的中點作爲根節點,對中點劃分出來的左右兩個鏈表遞歸調用函數,返回的節點分別爲根節點的左右孩子。


Java代碼實現:


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    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 pre = head;
        while(fast!=null && fast.next!=null)
        {
            fast = fast.next.next;
            pre = slow;
            slow = slow.next;
        }
        
        TreeNode root = new TreeNode(slow.val);
        pre.next = null;
        TreeNode left = sortedListToBST(head);
        TreeNode right = sortedListToBST(slow.next);
        root.left = left;
        root.right = right;
        
        return root;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章