根据有序链表构造平衡的二叉查找树
Posted zhuge134
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了根据有序链表构造平衡的二叉查找树相关的知识,希望对你有一定的参考价值。
leetcode地址:
https://leetcode.com/problems/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.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted linked list: [-10,-3,0,5,9], One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 0 / -3 9 / / -10 5
解题思路:
分为两步:
1. 把链表转存到一个数组中,问题转化为:将一个有序数组转化为一个平衡二叉查找树。
2. 取数组的中点为根节点,那么根节点的左子树是由左半边的数组生成的,右子树是由数组右半边生成的,分别对数组左半边和右半边进行递归调用
代码:
public class SortedListToBST
public TreeNode sortedListToBST(ListNode head)
int size = 0;
ListNode p = head;
while (p != null)
size++;
p = p.next;
ListNode[] listNodes = new ListNode[size];
p = head;
int index = 0;
while (p != null)
listNodes[index++] = p;
p = p.next;
return sortedListToBST(listNodes, 0, listNodes.length);
public TreeNode sortedListToBST(ListNode[] listNodes, int start, int end)
if (start >= end)
return null;
int mid = (end + start) / 2;
TreeNode root = new TreeNode(listNodes[mid].val);
root.left = sortedListToBST(listNodes, start, mid);
root.right = sortedListToBST(listNodes, mid + 1, end);
return root;
以上是关于根据有序链表构造平衡的二叉查找树的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode练习(Python):链表类:第109题:有序链表转换二叉搜索树:给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。 本题中,一个高度平衡二叉树是指一个二叉树每个