You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
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:
这道题要求把有序链表转化为高度优先的二叉搜索树。
受108. Convert Sorted Array to Binary Search Tree的启发,我们可以遍历链表,将节点的值域依次存入数组中,得到一个有序数组,然后利用二分法和先序创建二叉树的方法得到目标的高度优先的BST。
当然我们可以在原链表基础上操作,不需要转化为数组。思路就是先利用快慢指针找到当前链表的中间节点的前一个节点,然后同样利用先序遍历创建二叉树的思路,为了方便断开链表,首先创建右子节点,从中间断开链表后再创建左子节点,递归即可。重点是如何规划代码逻辑。
参考资料:
The text was updated successfully, but these errors were encountered: