Leetcode Convert Sorted List to Binary Search Tree 把有序链表转换成二叉搜索树

来源:互联网 发布:vscode reactjs 插件 编辑:程序博客网 时间:2024/05/17 02:15


题目:


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


分析:

举一个例子, 假如链表为 1--> 2 --> 3 --> 4 --> 5 --> 6 --> 7。 根据二叉搜索树的性质 root.val > left.val && root.val < right.val, 转换成二叉搜索树应该是

  4

        /    \

      2       6

   /     \    /    \

 1      3  5     7

从这个例子可以看出,链表的中间节点是树的根节点,中间节点把链表分成左右两部分,左右两个链表的中点又分别是根节点左右子树的根节点。因此,最容易想到用递归的方法。

1. 递归的结束条件是当节点为空或节点的next为空。节点为空则返回空,节点的next为空则返回该节点对应的树节点。

2. 找链表的中点作为根节点,对中点划分出来的左右两个链表递归调用函数,返回的节点分别为根节点的左右孩子。


Java代码实现:


/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } *//** * Definition for a binary tree node. * 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);                    ListNode slow = head;        ListNode fast = head;        ListNode pre = head;        while(fast!=null && fast.next!=null)        {            fast = fast.next.next;            pre = slow;            slow = slow.next;        }                TreeNode root = new TreeNode(slow.val);        pre.next = null;        TreeNode left = sortedListToBST(head);        TreeNode right = sortedListToBST(slow.next);        root.left = left;        root.right = right;                return root;    }}


0 0
原创粉丝点击