Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

108. Convert Sorted Array to Binary Search Tree #244

Open
Tcdian opened this issue Jul 3, 2020 · 1 comment
Open

108. Convert Sorted Array to Binary Search Tree #244

Tcdian opened this issue Jul 3, 2020 · 1 comment
Labels

Comments

@Tcdian
Copy link
Owner

Tcdian commented Jul 3, 2020

108. Convert Sorted Array to Binary Search Tree

将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。

本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1

Example

Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5
@Tcdian Tcdian added the Tree label Jul 3, 2020
@Tcdian
Copy link
Owner Author

Tcdian commented Jul 3, 2020

Solution

  • JavaScript Solution
/**
 * 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 {number[]} nums
 * @return {TreeNode}
 */
var sortedArrayToBST = function(nums) {
    return buildBST(0, nums.length - 1);

    function buildBST(left, right) {
        if (left > right) {
            return null;
        }
        const mid = (left + right) >> 1;
        const node = new TreeNode(nums[mid]);
        node.left = buildBST(left, mid - 1);
        node.right = buildBST(mid + 1, right);
        return node;
    }
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant