码迷,mamicode.com
首页 > 编程语言 > 详细

使用排序数组/链表构建二叉搜索树

时间:2018-08-13 14:07:39      阅读:163      评论:0      收藏:0      [点我收藏+]

标签: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;
    }

 

使用排序数组/链表构建二叉搜索树

标签:treenode   root   convert   help   vat   分享图片   ima   nod   png   

原文地址:https://www.cnblogs.com/TIMHY/p/9467145.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!