109.有序链表转换二叉搜索树
题目描述
Leetcode:https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree
给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定的有序链表: [-10, -3, 0, 5, 9],
一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:
解题思路
中序遍历模拟,用二分法来递归模拟
java代码
/**
* 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 {
private ListNode head;
private int findSize(ListNode head){
ListNode ptr = head;
int c = 0;
while(ptr != null){
ptr = ptr.next;
c += 1;
}
return c;
}
public TreeNode sortedListToBST(ListNode head) {
int size = this.findSize(head);
this.head = head;
return this.convertToBST(0, size - 1);
}
public TreeNode convertToBST(int l, int r){
if(l > r) return null;
int mid = (l + r) / 2;
TreeNode left = this.convertToBST(l, mid - 1);
TreeNode node = new TreeNode(head.val);
node.left = left;
this.head = this.head.next;
node.right = this.convertToBST(mid + 1, r);
return node;
}
}
python代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findSize(self, head: ListNode) -> int:
ptr = head
c = 0
while ptr:
ptr = ptr.next
c +=1
return c
def sortedListToBST(self, head: ListNode) -> TreeNode:
size = self.findSize(head)
def convert(l: int, r: int) -> TreeNode:
nonlocal head
if l > r:
return None
mid = (l + r) // 2
left = convert(l, mid - 1)
node = TreeNode(head.val)
node.left = left
head = head.next
node.right = convert(mid + 1, r)
return node
return convert(0, size - 1)