Zheaoli / do-something-right

MIT License
37 stars 3 forks source link

2022-10-18 #394

Open Zheaoli opened 1 year ago

Zheaoli commented 1 year ago

2022-10-18

gongpeione commented 1 year ago
/*
 * @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

微信id: 弘树 来自 vscode 插件