zoukankan      html  css  js  c++  java
  • 【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;
        }
  • 相关阅读:
    Nokia N8手机上开发Qt应用程序第一步:配置手机,使其支持Qt应用程序的运行
    Visual Studio 2010 "工具">"选项"中的VC++目录编辑功能已被否决
    删除用户 ORA04098
    把Excel转换成DataTable
    可编辑的DIV
    RDLC 错误号.
    leetcode| Add Digits
    leetcode| Integer to English Words
    leetcode|Counting Bits
    锁表了。。。
  • 原文地址:https://www.cnblogs.com/yumiaomiao/p/8487890.html
Copyright © 2011-2022 走看看