LeetCode 43 Convert Sorted List to Binary Search Tree

来源:互联网 发布:中国移动m823软件 编辑:程序博客网 时间:2024/06/07 09:19

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

分析:

看见二叉树,先想递归。

排序的链表,要转换成平衡二叉树,则中间节点应为root,再递归对前后两段建平衡二叉树就可以了。

找中间节点,则用快慢指针法。

/** * 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) {        return sortedListToBST(head, null);    }    private TreeNode sortedListToBST(ListNode head, ListNode tail){        if(head==null || head==tail)            return null;        ListNode fast = head;        ListNode slow = head;        while(fast != tail && fast.next != tail){            fast = fast.next.next;            slow = slow.next;        }        TreeNode root = new TreeNode(slow.val);        root.left = sortedListToBST(head, slow);        root.right = sortedListToBST(slow.next, tail);        return root;    }}


0 0