Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
原题链接:https://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
题目:给定一个有正序链表,将其转换成一个二叉搜索树。
思路:可以按照之前的数组的思路来做。即找到中间值,再左右递归建树。
public TreeNode sortedListToBST(ListNode head) {
if (head == null)
return null;
int len = 0;
ListNode tmp = head;
while (tmp != null) {
tmp = tmp.next;
len++;
}
return sortedListToBST(head, len);
}
public TreeNode sortedListToBST(ListNode head, int len) {
if (len <= 0)
return null;
int mid = (1 + len) / 2;
ListNode p = head;
int tmp = mid - 1;
while (tmp > 0) {
p = p.next;
tmp--;
}
TreeNode root = new TreeNode(p.val);
root.left = sortedListToBST(head, mid - 1);
root.right = sortedListToBST(p.next, len - mid);
return root;
}
// Definition for singly-linked list.
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
// Definition for binary tree
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
本文介绍了一种将有序链表转化为高度平衡的二叉搜索树的方法。通过寻找链表中间元素作为根节点,并递归地构造左右子树,最终实现链表到二叉树的转换。
183

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



