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

版权声明: https://blog.csdn.net/qq_38386316/article/details/83033169

题目描述

给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点的左右两个子树的高度差的绝对值不超过1.

示例

  • 给定的有序链表: [ 10 , 3 , 0 , 5 , 9 ] [-10, -3, 0, 5, 9]
  • 一个可能的答案是: [ 0 , 3 , 9 , 10 , n u l l , 5 ] [0, -3, 9, -10, null, 5] , 他表示的高度平衡二叉搜索树(就是以层序遍历的书写格式)。

思路
因为链表是有序的,我们递归时每次把中间的数加为节点进行构造二叉树就可以了,这个每次找链表的中间节点依旧可以使用快慢指针的方法进行找。找中间节点和构造二叉树便是此题的重点啦,找中间的节点也可以使用数组,就是把链表的数据都存到数组中,然后每次找中间的节点。

代码 * 1

class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        if(head == null) return null;
        return createTree(head, null);
    }
    public TreeNode createTree(ListNode head, ListNode tail) {
        if(head == tail ) return null;
        ListNode fast = head;
        ListNode slow = head;
        while(fast != tail && fast.next != tail) {
            fast = fast.next.next;
            slow = slow.next;
        }
        TreeNode node = new TreeNode(slow.val);
        node.left = createTree(head, slow);
        node.right = createTree(slow.next, tail);
        return node;
    } 
}

复杂度分析

  • 时间复杂度 O ( N ) O(N)
  • 空间复杂度 O ( N ) O(N)

代码 * 2

class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        if(head == null) 
            return null;
        ListNode node = head;
        int len = 0;
        while(node != null) {
            len ++;
            node = node.next;
        }
        int[] nums = new int[len];
        int k = 0;
        while(head != null){
            nums[k++] = head.val;
            head = head.next;
        }
        return CreateTree(nums, 0, nums.length - 1);
    }
    public TreeNode  CreateTree(int []nums, int  start, int end){
        if(start > end)
            return null;
        int mid = (start + end) /2;
        TreeNode head = new TreeNode(nums[mid]);
        head.left = CreateTree(nums, start, mid- 1);
        head.right = CreateTree(nums, mid+ 1, end);
        return head;
    }
}

复杂度分析

  • 时间复杂度 O ( N ) O(N)
  • 空间复杂度 O ( N ) O(N)

完整代码

package leetcode109;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;

/**
 * Created by 张超帅 on 2018/10/12.
 */
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}
class ListNode {
    int val;
    ListNode next;
    ListNode(int val) { this.val = val;}
}
class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        if(head == null) return null;
        return createTree(head, null);
    }
    public TreeNode createTree(ListNode head, ListNode tail) {
        if(head == tail ) return null;
        ListNode fast = head;
        ListNode slow = head;
        while(fast != tail && fast.next != tail) {
            fast = fast.next.next;
            slow = slow.next;
        }
        TreeNode node = new TreeNode(slow.val);
        node.left = createTree(head, slow);
        node.right = createTree(slow.next, tail);
        return node;
    }
}
public class leetcode109 {
    public static int[] stringToArrays(String input) {
        input = input.trim();
        input = input.substring(1, input.length() - 1);
        if(input == null) {
            return new int[0];
        }
        String[] patrs = input.split(",");
        int[] res = new int[patrs.length];
        for(int i = 0; i < res.length; i ++) {
            res[i] = Integer.parseInt(patrs[i].trim());
        }
        return res;
    }
    public static ListNode stringToListNode(String input) {
        int[] nodes = stringToArrays(input);
        ListNode dummpy = new ListNode(-1);
        ListNode cur = dummpy;
        for(int x : nodes) {
            cur.next = new ListNode(x);
            cur = cur.next;
        }
        return dummpy.next;
    }
    public static String treeNodeToString(TreeNode root) {
        if(root == null) {
            return "[]";
        }
        String ouput = "";
        Queue<TreeNode> nodeQueue = new LinkedList<>();
        nodeQueue.add(root);
        while(!nodeQueue.isEmpty()) {
            TreeNode node = nodeQueue.remove();
            if(node == null) {
                ouput += "null, ";
                continue;
            }
            ouput += String.valueOf(node.val) + ", ";
            nodeQueue.add(node.left);
            nodeQueue.add(node.right);
        }
        return "[" + ouput.substring(0, ouput.length() - 2) + "]";
    }
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String line = null;
        while((line = in.readLine()) != null) {
            ListNode head = stringToListNode(line);
            TreeNode res = new Solution().sortedListToBST(head);
            String result = treeNodeToString(res);
            System.out.println(result);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38386316/article/details/83033169