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;
        }
    }
    
  • 相关阅读:
    PL/SQL 训练05--游标
    PL/SQL 训练04--事务
    PL/SQL 训练03 --异常
    PL/SQL 训练02--集合数组
    PL/SQL 训练01--基础介绍
    25 mysql怎么保证高可用
    pt工具之pt-archiver
    Oracle日常性能问题查看
    Oracle的cursor
    Oracle 索引扫描的几种情况
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8719463.html
Copyright © 2011-2022 走看看