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

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; next = null; }
     7  * }
     8  */
     9 /**
    10  * Definition for binary tree
    11  * public class TreeNode {
    12  *     int val;
    13  *     TreeNode left;
    14  *     TreeNode right;
    15  *     TreeNode(int x) { val = x; }
    16  * }
    17  */
    18 public class Solution {
    19     public TreeNode sortedListToBST(ListNode head) {
    20         ArrayList<ListNode> listNodes=new ArrayList<ListNode>();
    21         if (head==null) return null;
    22         ListNode node=head;
    23         while (node!=null) {
    24             listNodes.add(node);
    25             node=node.next;
    26         }
    27         int middle=(listNodes.size()-1)/2;
    28         TreeNode root =new TreeNode(listNodes.get(middle).val);
    29         if (middle>0){
    30             listNodes.get(middle-1).next=null;
    31             root.left=sortedListToBST(listNodes.get(0));
    32 
    33         }
    34         if (middle<listNodes.size()-1){
    35             root.right=sortedListToBST(listNodes.get(middle+1));
    36 
    37         }
    38         return root;
    39 
    40     }
    41 }
  • 相关阅读:
    检测一个对象方法是否存在
    非堵塞 延迟脚本 高性能
    移动开发 相关 备忘
    元素透明 渐变函数
    cookie
    media query 单位
    前端入门可参考《如何教会非计算机专业的女友写代码》
    JQ判断复选框是否选中
    聊天记录
    JS获取文本值
  • 原文地址:https://www.cnblogs.com/birdhack/p/4072490.html
Copyright © 2020-2023  润新知