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;
        }
    }
  • 相关阅读:
    福大软工 · 第十次作业
    最终作业:软工实践个人总结
    第三视角Beta答辩总结
    Beta 冲刺(7/7)
    Beta 冲刺 (6/7)
    Beta 冲刺 (5/7)
    Beta 冲刺 (4/7)
    Beta 冲刺 (3/7)
    Beta 冲刺 (2/7)
    福大软工 · 第十次作业
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4665969.html
Copyright © 2011-2022 走看看