1 題目
給定一個單鏈表,其中的元素按升序排序,將其轉換爲高度平衡的二叉搜索樹。
本題中,一個高度平衡二叉樹是指一個二叉樹每個節點 的左右兩個子樹的高度差的絕對值不超過 1。
示例:
給定的有序鏈表: [-10, -3, 0, 5, 9],
一個可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面這個高度平衡二叉搜索樹:
0
/
-3 9
/ /
-10 5
2 思路
這道題我是將鏈表轉換爲數組,然後再用遞歸的方法來劃分數組構造二叉樹的,題解有更巧妙的中序遍歷遞歸構造數
3代碼
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {ListNode} head
* @return {TreeNode}
*/
var sortedListToBST = function(head) {
if (!head) return null;
const nums = [];
while(head) {
nums.push(head.val);
head = head.next;
}
return d(nums, 0, nums.length - 1);
function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}
function d(arr, low, high) {
if (low > high) return null;
let mid = Math.floor((low + high) / 2);
let node = new TreeNode(arr[mid]);
node.left = d(arr, low, mid - 1);
node.right = d(arr, mid + 1, high);
return node;
}
};