飞道的博客

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

495人阅读  评论(0)

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

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

示例:

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

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

      0
     / \
   -3   9
   /   /
 -10  5

思路:

1)转换成数组再做

2)链表直接做,快慢指针,时间慢。

3)按中序遍历建树,这样可以顺序遍历链表建树即可。

3见代码


  
  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. /**
  10. * Definition for a binary tree node.
  11. * public class TreeNode {
  12. * int val;
  13. * TreeNode left;
  14. * TreeNode right;
  15. * TreeNode(int x) { val = x; }
  16. * }
  17. */
  18. /**
  19. * Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode(int
  20. * x) { val = x; } }
  21. */
  22. /**
  23. * Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode
  24. * right; TreeNode(int x) { val = x; } }
  25. */
  26. class Solution {
  27. private ListNode head;
  28. private int findSize(ListNode head) {
  29. ListNode ptr = head;
  30. int c = 0;
  31. while (ptr != null) {
  32. ptr = ptr.next;
  33. c += 1;
  34. }
  35. return c;
  36. }
  37. private TreeNode convertListToBST(int l, int r) {
  38. if (l > r) {
  39. return null;
  40. }
  41. int mid = (l + r) / 2;
  42. TreeNode left = this.convertListToBST(l, mid - 1);
  43. TreeNode node = new TreeNode( this.head.val);
  44. node.left = left;
  45. this.head = this.head.next;
  46. node.right = this.convertListToBST(mid + 1, r);
  47. return node;
  48. }
  49. public TreeNode sortedListToBST(ListNode head) {
  50. int size = this.findSize(head);
  51. this.head = head;
  52. return convertListToBST( 0, size - 1);
  53. }
  54. }

 


转载:https://blog.csdn.net/hebtu666/article/details/103933884
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场