zoukankan      html  css  js  c++  java
  • 109 Convert Sorted List to Binary Search Tree 有序链表转换二叉搜索树

    给定一个单元链表,元素按升序排序,将其转换为高度平衡的BST。
    对于这个问题,一个高度平衡的二叉树是指:其中每个节点的两个子树的深度相差不会超过 1 的二叉树。
    示例:
    给定的排序链表: [-10, -3, 0, 5, 9],
    则一个可能的答案是:[0, -3, 9, -10, null, 5]
          0
         /
       -3   9
       /   /
     -10  5
    详见:https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/description/

    Java实现:

    /**
     * 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; }
     * }
     */
    class Solution {
        public TreeNode sortedListToBST(ListNode head) {
            if(head==null){
                return null;
            }
            if(head!=null&&head.next==null){
                return new TreeNode(head.val);
            }
            ListNode slow=head;
            ListNode fast=head;
            ListNode pre=null;
            while(fast!=null&&fast.next!=null){
                pre=slow;
                slow=slow.next;
                fast=fast.next.next;
            }
            TreeNode root=new TreeNode(slow.val);
            if(pre!=null){
                pre.next=null;
            }
            root.left=sortedListToBST(head);
            root.right=sortedListToBST(slow.next);
            return root;
        }
    }
    
  • 相关阅读:
    小程序模板template问题记录
    datepicker 组件 的坑
    js实现 throttle 和 debounce
    vuex简单使用
    webpack 打包图片 缺失问题
    invalid prop `current` of type `string` supplied to `pagination`, expected `
    HTML5自定义属性之data-*
    vue组件传值方式介绍
    解决github.com 打不开问题
    git密令使用
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8719463.html
Copyright © 2011-2022 走看看