链表 有序链表转换二叉搜索树

2020-06-20 14:46 更新

题目

给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。

本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。

示例:

给定的有序链表: [-10, -3, 0, 5, 9],

一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:

  1. 0
  2. / \
  3. -3 9
  4. / /
  5. -10 5

解题

  1. /**
  2. * Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode(int
  3. * x) { val = x; } }
  4. */
  5. /**
  6. * Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode
  7. * right; TreeNode(int x) { val = x; } }
  8. */
  9. class Solution {
  10. private ListNode findMiddleElement(ListNode head) {
  11. // The pointer used to disconnect the left half from the mid node.
  12. ListNode prevPtr = null;
  13. ListNode slowPtr = head;
  14. ListNode fastPtr = head;
  15. // Iterate until fastPr doesn't reach the end of the linked list.
  16. while (fastPtr != null && fastPtr.next != null) {
  17. prevPtr = slowPtr;
  18. slowPtr = slowPtr.next;
  19. fastPtr = fastPtr.next.next;
  20. }
  21. // Handling the case when slowPtr was equal to head.
  22. if (prevPtr != null) {
  23. prevPtr.next = null;
  24. }
  25. return slowPtr;
  26. }
  27. public TreeNode sortedListToBST(ListNode head) {
  28. // If the head doesn't exist, then the linked list is empty
  29. if (head == null) {
  30. return null;
  31. }
  32. // Find the middle element for the list.
  33. ListNode mid = this.findMiddleElement(head);
  34. // The mid becomes the root of the BST.
  35. TreeNode node = new TreeNode(mid.val);
  36. // Base case when there is just one element in the linked list
  37. if (head == mid) {
  38. return node;
  39. }
  40. // Recursively form balanced BSTs using the left and right halves of the original list.
  41. node.left = this.sortedListToBST(head);
  42. node.right = this.sortedListToBST(mid.next);
  43. return node;
  44. }
  45. }
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号