题目的链接在这里:https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree/
题目大意
给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
一、示意图
二、解题思路
递归
递归
代码如下:
/**
* 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;
}
//还需要一个根节点的判断
if(head.next==null){
//说明没有节点了
TreeNode root=new TreeNode(head.val);
return root;
}
int length=0;
ListNode head1=head;
ListNode temp=head;
ListNode left=head;
while (head!=null){
head=head.next;
length++;
}
System.out.println("length = " + length);
//再把这个链表一分为二
//左边的怎么分呢 不如连接到另一个上去
//先找到根节点
int find=length/2-1;
length/=2;
while (length>0){
head1=head1.next;
length--;
}
// System.out.println("head1.val = " + head1.val);
//这个的作用只是找到那个中点位置
TreeNode root=new TreeNode(head1.val);
//然后找到左边的节点
while (find>0){
temp=temp.next;
find--;
}
// System.out.println("temp.val = " + temp.val);
//然后切点temp
temp.next=null;
//这样left就是指向左子树了
ListNode right=head1.next;
//这个之后head指向那个节点
root.left=sortedListToBST(left);
root.right=sortedListToBST(right);
return root;
}
}