*LeetCode-Convert Sorted List to Binary Search Tree

35 篇文章 0 订阅
24 篇文章 0 订阅

inorder就是顺序的一个linked list

每次找到list的中间 就是root 左边sub list中间就是左子 右边sub list的中间就是右子

但是注意只有一个node的情况 要把head设置成null 而且每次找到mid之后  要把mid之前的那个node.next = null 

o(nlogn)

public class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        if ( head == null )
            return null;
         ListNode fast = head;
         ListNode slow = head;
         ListNode pre = null;
         while ( fast != null && fast.next != null ){
             fast = fast.next.next;
             pre = slow;
             slow = slow.next;
         }
         if ( pre != null )
            pre.next = null;
        else
            head = null;
         TreeNode root = new TreeNode ( slow.val );
         root.left = sortedListToBST(head);
         root.right = sortedListToBST(slow.next);
         return root;
    }
}
o(n)做法

The method 1 constructs the tree from root to leaves. In this method, we construct from leaves to root. The idea is to insert nodes in BST in the same order as the appear in Linked List, so that the tree can be constructed in O(n) time complexity. We first count the number of nodes in the given Linked List. Let the count be n. After counting nodes, we take left n/2 nodes and recursively construct the left subtree. After left subtree is constructed, we allocate memory for root and link the left subtree with root. Finally, we recursively construct the right subtree and link it with root.

While constructing the BST, we also keep moving the list head pointer to next so that we have the appropriate pointer in each recursive call.

从list头开始 用一个全局指针来当pointer 每次建好左树 建一个rootnode pointer ++ 然后建右树 

每个node访问一遍 就是inorder的顺序 bottom up做的

public class Solution {
    private ListNode node;
    public TreeNode sortedListToBST(ListNode head) {
        if ( head == null )
            return null;
        ListNode pt = head;
        node = head;
        int count = 0; 
        while ( head != null ){
            head = head.next;
            count ++;
        }
        return helper ( 0, count - 1 );
    }
    public TreeNode helper ( int start, int end ){
        if ( start > end )
            return null;
        int mid = start + ( end - start ) / 2;
        TreeNode left = helper ( start, mid - 1 );
        TreeNode root = new TreeNode ( node.val );
        root.left = left;
        node = node.next;
        root.right = helper ( mid + 1, end );
        return root;
    }

helper里面的start end只是用来计数的 我觉得 为了判断停止条件



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值