• 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.

    用空间换时间的方法,先用一个数组将节点按序存放,然后建树,代码如下:

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; next = null; }
     * }
     */
    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        
        private List<TreeNode> list = new ArrayList<TreeNode>();
        
        public TreeNode creatBST(int low,int high) {
            if(low<=high) {
                int mid = (high+low)/2;
                TreeNode root = list.get(mid);
                root.left = creatBST(low,mid-1);
                root.right = creatBST(mid+1,high);
                return root;
            }
            else return null;
          
        }
        
        public TreeNode sortedListToBST(ListNode head) {
            while(head!=null) {
                TreeNode node = new TreeNode(head.val);
                list.add(node);
                head = head.next;
            }
            return creatBST(0,list.size()-1);
    
        }
    }
  • 相关阅读:
    mysql批量导入删除
    sql查重去除id最小值
    Rest构建分布式 SpringCloud微服务架构项目
    Django模板语言及视图
    Django模板语言
    面向对象进阶
    初识面向对象
    os模块和sys模块
    random模
    时间模块
  • 原文地址:https://www.cnblogs.com/mrpod2g/p/4415692.html
Copyright © 2020-2023  润新知