来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
给定一个单链表的头节点 head ,其中的元素 按升序排序 ,将其转换为高度平衡的二叉搜索树。 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差不超过 1。
解答
解题思路:
- 链表转为升序数组
- 升序数组转二叉搜索树原则:二分查找根节点
/*** Definition for singly-linked list.* function ListNode(val, next) {* this.val = (val===undefined ? 0 : val)* this.next = (next===undefined ? null : next)* }*//*** Definition for a binary tree node.* function TreeNode(val, left, right) {* this.val = (val===undefined ? 0 : val)* this.left = (left===undefined ? null : left)* this.right = (right===undefined ? null : right)* }*//*** @param {ListNode} head* @return {TreeNode}*/function listToArray (head) {let nodes = [];while (head) {nodes.push(head.val);head = head.next;}return nodes;}function arrayToTree (nodes) {if (!nodes || !nodes.length) return null;const mid = nodes.length >> 1;const rootVal = nodes[mid];const root = new TreeNode(rootVal);root.left = arrayToTree(nodes.slice(0, mid));root.right = arrayToTree(nodes.slice(mid + 1));return root;}var sortedListToBST = function(head) {const nodes = listToArray(head);return arrayToTree(nodes);};
