Leetcode109. Convert Sorted List to Binary Search Tree

Posted 于淼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode109. 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;
    }

 

以上是关于Leetcode109. Convert Sorted List to Binary Search Tree的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 109. Convert Sorted List to Binary Search Tree

Leetcode109. Convert Sorted List to Binary Search Tree

LeetCode-109-Convert Sorted List to Binary Search Tree

leetcode109. Convert Sorted List to Binary Search Tree

[Leetcode]109. Convert Sorted List to Binary Search Tree

Leetcode 109: Convert Sorted List to Binary Search Tree