【二叉树的中序遍历】109. 有序链表转换二叉搜索树

109. 有序链表转换二叉搜索树

解题思路

  • 二叉搜索树的中序遍历是有序的
  • 那么寻找一个单链表的中点,然后作为根节点
  • 之后递归左边链表,递归右边链表


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        // 因为链表是有序的 二叉搜索树是找链表中点 
        // 二叉搜索树的中序遍历就是 链表有序

        if(head == null){
            return null;
        }

        return  helper(head,null);

    }

    private TreeNode helper(ListNode head,ListNode tail){
        if(head == tail){
            return null;
        }

        // 计算链表的中点  使用快慢指针
        ListNode slow = head;
        ListNode fast = head;


        while(fast != tail && fast.next != tail){
            slow = slow.next;
            fast = fast.next.next;
        }

        // 递归
        TreeNode root = new TreeNode(slow.val);// 使用中点作为根节点
        root.left = helper(head,slow);
        root.right = helper(slow.next,tail);
        return root;
    }
}

你可能感兴趣的:(#,Leetcode,链表,数据结构)