来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

给定一个单链表的头节点 head ,其中的元素 按升序排序 ,将其转换为高度平衡的二叉搜索树。 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差不超过 1。

解答

解题思路:

  1. 链表转为升序数组
  2. 升序数组转二叉搜索树原则:二分查找根节点
    1. /**
    2. * Definition for singly-linked list.
    3. * function ListNode(val, next) {
    4. * this.val = (val===undefined ? 0 : val)
    5. * this.next = (next===undefined ? null : next)
    6. * }
    7. */
    8. /**
    9. * Definition for a binary tree node.
    10. * function TreeNode(val, left, right) {
    11. * this.val = (val===undefined ? 0 : val)
    12. * this.left = (left===undefined ? null : left)
    13. * this.right = (right===undefined ? null : right)
    14. * }
    15. */
    16. /**
    17. * @param {ListNode} head
    18. * @return {TreeNode}
    19. */
    20. function listToArray (head) {
    21. let nodes = [];
    22. while (head) {
    23. nodes.push(head.val);
    24. head = head.next;
    25. }
    26. return nodes;
    27. }
    28. function arrayToTree (nodes) {
    29. if (!nodes || !nodes.length) return null;
    30. const mid = nodes.length >> 1;
    31. const rootVal = nodes[mid];
    32. const root = new TreeNode(rootVal);
    33. root.left = arrayToTree(nodes.slice(0, mid));
    34. root.right = arrayToTree(nodes.slice(mid + 1));
    35. return root;
    36. }
    37. var sortedListToBST = function(head) {
    38. const nodes = listToArray(head);
    39. return arrayToTree(nodes);
    40. };