zoukankan      html  css  js  c++  java
  • [leetcode]Convert Sorted List to Binary Search Tree

    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.

    算法思路:

    [leetcode]Convert Sorted Array to Binary Search Tree很相似,不过一个是array,一个是list,无本质区别。

    三步走:

    找中点(快慢指针)

    断链表(需要找慢指针的前驱)

    分治。

    代码如下:

     1 public class Solution {
     2     public TreeNode sortedListToBST(ListNode head) {
     3         if(head == null) return null;
     4         if(head.next == null) return new TreeNode(head.val);
     5         ListNode hhead = new ListNode(0);
     6         hhead.next = head;
     7         ListNode fast = hhead, slow= hhead;
     8         while(fast != null && fast.next != null){
     9             fast = fast.next.next;
    10             slow = slow.next;
    11         }
    12         TreeNode root = new TreeNode(slow.val);
    13         ListNode right = slow.next;
    14         ListNode pre = hhead;
    15         while(pre != null && pre.next != slow){
    16             pre = pre.next;
    17         }
    18         pre.next = null;
    19         ListNode left = hhead.next;
    20         root.left = sortedListToBST(left);
    21         root.right = sortedListToBST(right);
    22         return root;
    23     }
    24 }
  • 相关阅读:
    四月⑨日
    4月⑦日
    4月6日
    四月⑧日
    第一天上课
    modelsim的do文件
    SCCB协议
    FPGA之VGA控制
    FPGA常用术语
    乘法器之六(硬件乘法器)
  • 原文地址:https://www.cnblogs.com/huntfor/p/3916168.html
Copyright © 2011-2022 走看看