本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定的有序链表: [-10, -3, 0, 5, 9],
一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解:
- 树的很多问题都是需要:递归建树
- 如果给定数组可以采用区间left、right递归
- 本题给定链表,可以改造现有结点建树
- 找出链表中间结点,断开与前后连接(如果不断开与pre的联系在left递归时还会出现本结点),前半段接left、后半段接right
/**
* 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; }
* }
*/
class Solution {
public TreeNode sortedListToBST(ListNode head) {
/**
1、树的很多问题都是需要:递归建树
2、如果给定数组可以采用区间left、right递归
3、本题给定链表,可以改造现有结点建树
4、找出链表中间结点,断开与前后连接,前半段接left、后半段接right、
*/
if(head==null){
return null;
}else if(head.next==null){//区间内1个结点
TreeNode next_root = new TreeNode(head.val);
return next_root;
}else if(head.next.next==null){//区间内2个结点
TreeNode next_root = new TreeNode(head.next.val);
next_root.left = new TreeNode(head.val);
next_root.right = null;
return next_root;
}
//区间内3个及以上结点
ListNode cur = new ListNode(-1);
cur.next = head;
ListNode mid = cur;//find mid of this list
while(cur!=null && cur.next!=null && cur.next.next!=null){
cur = cur.next.next;
mid = mid.next;
}
ListNode right_head = null;//右侧List起点
if(mid.next!=null){
right_head = mid.next.next;
}
//断开mid与前后结点的联系
mid.next.next = null;
TreeNode root = new TreeNode(mid.next.val);//每次总是以mid为根
mid.next = null;
//递归
root.left = sortedListToBST(head);
root.right = sortedListToBST(right_head);
return root;
}
}