zoukankan      html  css  js  c++  java
  • [leedcode 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.

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public TreeNode sortedListToBST(ListNode head) {
            if(head==null) return null;
            int len=0;
            ListNode node=head;
            while(node!=null){
                node=node.next;
                len++;
            }
            return getBST(head,0,len-1);
        }
        TreeNode getBST(ListNode head,int start,int end){
            if(start>end) return null;
            int mid=(start+end)/2;
            ListNode temp=head;
            for(int i=start;i<mid;i++){//求中间节点方法————start到mid
                temp=temp.next;
            }
            TreeNode node=new TreeNode(temp.val);
            node.left=getBST(head,start,mid-1);
            node.right=getBST(temp.next,mid+1,end);//注意右侧节点链表的头结点!!!因为和数组求中间节点的方式不一样,链表主要是遍历,求相对位置
            return node;
        }
    }
  • 相关阅读:
    学术诚信与职业道德
    第8,9,10章读后感
    Scrum项目7.0
    燃尽图
    Scrum 项目4.0
    Sprint计划
    复利计算再升级——连接数据库
    软件工程---做汉堡,结对2.0
    软件工程---复利计算-结对
    学习进度条博客
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4665969.html
Copyright © 2011-2022 走看看