zoukankan      html  css  js  c++  java
  • LeetCode

    题目:

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

    思路:

    转化为数组,更容易搜寻中点

    package bst;
    
    class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }
    
    public class ConvertSortedListToBinarySearchTree {
    
        public TreeNode sortedListToBST(ListNode head) {
            int[] nums = convertListToArray(head);
            return constructBST(nums, 0, nums.length - 1);
        }
        
        private TreeNode constructBST(int[] nums, int start, int end) {
            if (start > end) return null;
            int mid = (end - start) / 2 + start;
            TreeNode root = new TreeNode(nums[mid]);
            root.left = constructBST(nums, start, mid - 1);
            root.right = constructBST(nums, mid + 1, end);
            return root;
        }
        
        private int[] convertListToArray(ListNode head) {
            ListNode p = head;
            int count = 0;
            while (head != null) {
                ++count;
                head = head.next;
            }
            
            int[] nums = new int[count];
            count = 0;
            while (p != null) {
                nums[count++] = p.val;
                p = p.next;
            }
            
            return nums;
        }
        
    }
  • 相关阅读:
    7-30-组队赛
    POJ 3125 Printer Queue
    7-28-比赛
    POJ 3922 A simple stone game
    POJ 1845
    第一次组队训练
    I-number
    Radar Installation
    Robots on a grid(DP+bfs())
    Dividing a Chocolate(zoj 2705)
  • 原文地址:https://www.cnblogs.com/null00/p/5118138.html
Copyright © 2011-2022 走看看