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

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

    解题思路:

    同上题,JAVA实现如下:

        public TreeNode sortedListToBST(ListNode head) {
            ArrayList<Integer> list=new ArrayList<Integer>();
            while(head!=null){
            	list.add(head.val);
            	head=head.next;
            }
            return sortedListToBST(list,0,list.size()-1);
        }
    	static public TreeNode sortedListToBST(ArrayList<Integer> list, int begin, int end) {
    		if (begin>end)
    			return null;
    		TreeNode root = new TreeNode(list.get((begin+end) / 2));
    		root.left=sortedListToBST(list,begin,(begin+end) / 2-1);
    		root.right=sortedListToBST(list,(begin+end) / 2+1,end);
    		return root;
    	}
    
  • 相关阅读:
    C#
    数据库SQL Server
    JavaScript题目
    vscode: Visual Studio Code 常用快捷键
    jQuery教程
    JavaScript快速排序
    JS编程艺术
    JS
    linux 笔记
    积累的各种资源
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4524797.html
Copyright © 2011-2022 走看看