LeetCode_convert-sorted-list-to-binary-search-tree

题目描述:

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

思路:二叉查找树的中序遍历就是排序的数,那么我们可以通过中序遍历来构建这个树

直接看代码,下面一般是改进的 ,这里题目要求的是,当节点是偶数的时候,以n/2+1个作为中间节点。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; next = null; }
 * }
 */
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
//二叉查找树的中序遍历就是排序的数,那么我们可以通过中序遍历来构建这个树
public class Solution {
    
    public TreeNode sortedListToBST(ListNode head) {
        if(head==null)
            return null;
        if(head.next==null)
            return new TreeNode(head.val);
        //至少有两个节点才能用快慢节点切割,不然节点为1的时候 会出现分为 1,0这样的死循环
        ListNode fast=head;
        ListNode slow=head;
        ListNode pre=null;
        while(fast!=null&&fast.next!=null){
            pre=slow;
            slow=slow.next;
            fast=fast.next.next;
        }
        if(pre!=null)
            pre.next=null;
        ListNode mid=slow;//慢指针指向的就是中间节点
        ListNode nextHead=slow.next;

        TreeNode node=new TreeNode(mid.val);
        if(pre==null)
            node.left=sortedListToBST(null);
        else
            node.left=sortedListToBST(head);
        node.right=sortedListToBST(nextHead);
        return node;
    }
    
    //代码改进
    public TreeNode sortedListToBST(ListNode head) {
        return sortedListToBST(head,null);
    }
    private TreeNode sortedListToBST(ListNode head,ListNode end){
        if(head==end)
            return null;
        ListNode fast=head;
        ListNode slow=head;
        while(fast!=end&&fast.next!=end){
            fast=fast.next.next;
            slow=slow.next;
        }
        TreeNode root=new TreeNode(slow.val);
        root.left=sortedListToBST(head,slow);
        root.right=sortedListToBST(slow.next,end);
        return root;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_34144916/article/details/81136118
今日推荐