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;
        }
  • 相关阅读:
    Grid 网格布局
    final变量属性小记
    色温与光合作用
    自定义CheckBox
    关于final局部变量引用的研究
    面向空实现类继承
    Android tips tool 发现的性能问题(转载翻译)
    org.json与json-lib的区别(补充 FastJson)
    设计模式之禅——心得总结
    大学本科毕业论文——LanguageTool语法校正规则库的开发
  • 原文地址:https://www.cnblogs.com/yumiaomiao/p/8487890.html
Copyright © 2011-2022 走看看