LeetCode 109. 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:
1
2
3
4
5 0
/ \
-3 9
/ /
-10 5
分析:
这道题可以参考108题将数组转换成二叉搜索树的代码,我也是利用它来完成这道题目。
首先遍历链表,将其链表值存入vector数组中,然后和108题一样将数组转换成二叉搜索树。
具体过程为:找出中间数,作为根节点,然后将数组分成两半,递归求解即可。LeetCode上的Discuss有一个想法是将找出链表的中间节点:先初始化temp为head,然后用了一个循环,在循环里不断更新temp为
temp = temp->next->next;
,循环退出条件为temp != NULL && temp->next != NULL
,得到链表的中间节点,然后递归左右链表。具体代码在文章底部。
代码如下:
1 | // Definition for singly-linked list. |
Discuss:
1 |
|