zoukankan      html  css  js  c++  java
  • [LeetCode] 109. Convert Sorted List to Binary Search Tree Java

    题目:

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

    题意及分析:将一个升序链表转化为平衡二叉搜索树。根据平衡二叉搜索树的定义,我们可以每次取出数组的中间点作为根节点,然后左边子数组的中间点作为根节点的左子节点,右边子数组的中间点作为根节点的右子节点。这里可以用两种方式,一种是遍历链表两次,将链表转化为数组,那么就变成和上一题一样了;另一种是用两个指针得到链表的中间点。

    代码一转化为数组):

    public class Solution {
        public TreeNode sortedListToBST(ListNode head) {
            int size = 0;
            ListNode count = head;
            while(count!=null){
                size++;
                count=count.next;
            }
            int[] arr = new int[size];
            ListNode getArr = head;
            int index=0;
            while(getArr!=null){
                arr[index] = getArr.val;
                getArr = getArr.next;
                index++;
            }
            return build(0,size-1,arr);
        }
    
        public TreeNode build(int start,int end,int[] arr){
            if(end<start) return null;
            int mid = (start+end)/2;
            TreeNode root = new TreeNode(arr[mid]);
            root.left = build(start,mid-1,arr);
            root.right = build(mid+1,end,arr);
            return root;
        }
    }

    代码二(直接得到链表中点):

    public class Solution {
        public TreeNode sortedListToBST(ListNode head) {
            if(head==null) return  null;
            return build(head,null);
        }
    
        public TreeNode build(ListNode head,ListNode end){
            if(head==end) return null;
            ListNode fast = head;
            ListNode slow = head;
    
            while(fast!=end&&fast.next!=end){      //slow指向的点就是链表的中间点
                slow = slow.next;
                fast = fast.next.next;
            }
            TreeNode root = new TreeNode(slow.val);
            root.left = build(head,slow);
            root.right=build(slow.next,end);
            return root;
        }
    }
  • 相关阅读:
    几个shell自动化脚本(定期清理、磁盘空间、搜寻关键字)
    linux系统垃圾清理
    mysql出现Got error 28 from storage engine错误
    WebBindingInitializer学习
    Java多线程异步调度程序分析(二)
    自己封装的C#操作redis公共类
    Java多线程编程的常见陷阱(转)
    Java分布式优秀资源集合
    JVM GC之对象生死
    Java内存模型
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7232332.html
Copyright © 2011-2022 走看看