• 【Leetcode】109. Convert Sorted List to Binary Search Tree


    Question:

    Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

    For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

    Example:

    Given the sorted linked list: [-10,-3,0,5,9],
    
    One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
    
          0
         / 
       -3   9
       /   /
     -10  5
    

    Tips:

    给定一个有序的单链表,将其转换成一个平衡二叉查找树。

    思路:

    (1)找到链表的中间位置,作为BST的根节点。方法就是设置两个指针,fast、slow,slow每次走一步,fast每次走两步。当fast先遇到null,slow就指向链表中间节点。

    (2)左、右子树的根节点也用相同的方法找到,并作为根节点的左右子树。接下来的结点可用递归来解决。

    代码:

    public TreeNode sortedListToBST(ListNode head){
            if(head==null) return null;
            return toBST(head,null);
        }
    
        private TreeNode toBST(ListNode head,ListNode tail) {
            if(head==tail) return null;
            ListNode fast=head;
            ListNode slow=head;
            //循环找到链表中间位置作为根节点。
            while(fast!=tail && fast.next!=tail){
                slow=slow.next;
                fast=fast.next.next;
            }
            TreeNode root=new TreeNode(slow.val);
            root.left=toBST(head,slow);
            root.right=toBST(slow.next,tail);
            return root;
        }
  • 相关阅读:
    python 之Twsited
    python之 rabbitmq
    python 之redis
    异常处理
    python select
    线程与进程
    初识socket
    Position属性
    Http协议理解
    BFC(块级格式化上下文)
  • 原文地址:https://www.cnblogs.com/yumiaomiao/p/8487890.html
Copyright © 2020-2023  润新知