Convert Sorted List to Binary Search Tree
Description
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/*
* @param head: The first node of linked list.
* @return: a tree node
*/
ListNode list ;
public TreeNode sortedListToBST(ListNode head) {
// write your code here
int n = getSize(head);
list = head;
TreeNode root = toBST(0 , n-1) ;
return root ;
}
public int getSize(ListNode node){
int size=0 ;
while(node != null){
size++ ;
node = node.next ;
}
return size ;
}
public TreeNode toBST(int L , int R){
if (L > R){
return null ;
}
int mid = (L + R)>>>1 ;
TreeNode left = toBST(L , mid-1);
//TreeNode right = toBST(mid+1 , R);
TreeNode curt = new TreeNode(list.val);
list = list.next ;
//TreeNode left = toBST(L , mid-1);
curt.left = left ;
TreeNode right = toBST(mid+1 , R);
curt.right = right ;
return curt ;
}
}
有序链表转化为平衡二叉搜索树
该博客主要介绍了如何将一个升序排列的单链表转换为高度平衡的二叉搜索树。通过先计算链表长度,再递归地进行中序遍历和切割,确保生成的二叉树节点左右子树的高度差不超过1,同时保持节点值有序。
359

被折叠的 条评论
为什么被折叠?



