HZFE / algorithms-solving

1 stars 0 forks source link

2022-10-18 #81

Open github-actions[bot] opened 2 years ago

gongpeione commented 2 years ago

108 Convert Sorted Array to Binary Search Tree

/*
 * @lc app=leetcode id=108 lang=typescript
 *
 * [108] Convert Sorted Array to Binary Search Tree
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function sortedArrayToBST(nums: number[]): TreeNode | null {
    const helper = (l, r) => {
        if (l > r) {
            return null;
        }

        const m = ~~((l + r) / 2);
        const node = new TreeNode(
            nums[m],
            helper(l, m - 1),
            helper(m + 1, r)
        );

        return node;
    }

    return helper(0, nums.length - 1);
};
// @lc code=end

Nickname: Geeku From vscode-hzfe-algorithms