有序链表转换二叉搜索树
给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定的有序链表: [-10, -3, 0, 5, 9],
一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
思路+代码+注释:
TreeNode root=null;
public TreeNode sortedListToBST(ListNode head) {
/*
思路:二叉搜索树的特点就是左<根<右,那么使用左根右遍历后得到的数组就是有序的,查看数组的中间节点为当前树的根节点,
然后再递归查找左子树(左边的数组)的根节点设置为该节点的左子节点,递归查找右子树(右边的数组)的根节点设置为该节点的右子节点,本质就是二分查找
*/
List<Integer> source=new ArrayList<>();
while (head!=null)
{
source.add(head.val);
head=head.next;
}
sortedListToBST(source,0,source.size()-1,null,false,false);
return root;
}
private void sortedListToBST(List<Integer> source,int low,int high,TreeNode preRootNode,boolean left,boolean right)
{
if (low>high)
{
return;
}
int mid=(low+high)/2;
int val=source.get(mid);
TreeNode node=new TreeNode(val);
if (preRootNode==null)
{
root=node;
}
if (left)
{
preRootNode.left=node;
}
if (right)
{
preRootNode.right=node;
}
sortedListToBST(source,low,mid-1,node,true,false);
sortedListToBST(source,mid+1,high,node,false,true);
}