使用排序數組/鏈表構建二叉搜尋樹

來源:互聯網
上載者:User

標籤:treenode   root   convert   help   vat   分享圖片   ima   nod   png   

2018-08-13 11:29:05

一、Convert Sorted Array to Binary Search Tree

問題描述:

問題求解:

    public TreeNode sortedArrayToBST2(int[] nums) {        if (nums == null || nums.length == 0) {            return null;        }        return helper(0, nums.length - 1, nums);    }    private TreeNode helper (int start, int end, int[] nums) {        if (start > end) {            return null;        }        int mid= start + (end - start) / 2;        TreeNode root = new TreeNode(nums[mid]);        root.left = helper(start, mid - 1, nums);        root.right = helper(mid + 1, end , nums);        return root;    }

二、Convert Sorted List to Binary Search Tree

問題描述:

問題求解:

    public TreeNode sortedListToBST(ListNode head) {        if (head == null) return null;        return helper(head, null);    }    private TreeNode helper(ListNode head, ListNode tail) {        if (head == tail) return null;        ListNode mid = getMid(head, tail);        TreeNode root = new TreeNode(mid.val);        root.left = helper(head, mid);        root.right = helper(mid.next, tail);        return root;    }    private ListNode getMid(ListNode head, ListNode tail) {        ListNode slow = head;        ListNode fast = head;        while (fast != tail && fast.next != tail) {            slow = slow.next;            fast = fast.next.next;        }        return slow;    }

 

使用排序數組/鏈表構建二叉搜尋樹

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.