LeetCode109 將有序鏈表轉換爲二叉搜索樹

將有序鏈表轉換爲二叉搜索樹>>>

在這裏插入圖片描述

採用二分查找法:和數組的類似,將鏈表分爲兩部分,左邊的爲左子樹,右邊的爲右子樹

`package JDFS;


import java.util.ArrayList;
import java.util.List;

/**
 * @Author Zhou  jian
 * @Date 2020 ${month}  2020/4/30 0030  15:28
 * 與上提 還是找中點
 * 但這個是鏈表找中點,我們用快慢指針
 */
public class Problem109 {


    public TreeNode sortedListToBST(ListNode head) {

        if(head==null) return null;

        //鏈表的中間接點爲根節點,鏈表的左邊爲左子樹;
        //鏈表的右子樹爲右子樹

        return  dfs(head,null);
    }


    /**
     *
     * @param head
     * @param tail
     * @return
     */
    public TreeNode dfs(ListNode head,ListNode tail){

        if(head==tail) return null;

        //找到鏈表的中間節點
        /**
         * 1、快慢指針找到鏈表的中間節點
         * 2、此節點作爲二叉搜索樹的根節點
         * 3、中間節點左部分遞歸調用,構建成二叉搜索樹的左子樹,
         *      中間節點的右部分遞歸調用,構建成二叉樹搜索樹的右子樹
         * 4、
         */
        ListNode slow = head;
        ListNode quick = head;

        while(quick!=tail&&quick.next!=tail){
            quick=quick.next.next;
            slow=slow.next;
        }

        TreeNode node = new TreeNode(slow.val);
        //
        node.left=dfs(head,slow);
        node.right=dfs(slow.next,tail);


        return  node;



    }



/////////////////////////////////////////////////
/////////////////////////////////////
//////////////////////////////////////////////

    //遍歷鏈表,將值存入數組,數組值爲二叉樹的中序遍歷值,使用遞歸還原
    //方法1:
    public TreeNode sortedListToBST1(ListNode head) {
        //1.遍歷鏈表,使用數組保留節點升序值
        List<Integer> list = new ArrayList<>();
        while(head != null){
            list.add(head.val);
            head = head.next;
        }

        //2.遞歸構建二叉樹,鏈表值爲中序遍歷結果
        return helper(list,0,list.size()-1);
    }

    private TreeNode helper(List<Integer> list, int lo, int hi) {
        if(lo > hi) return null;
        int mid = lo + (hi-lo)/2;
        TreeNode root = new TreeNode(list.get(mid));
        root.left = helper(list,lo,mid-1);
        root.right = helper(list,mid+1,hi);
        return root;
    }




}


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