ZhongKuo0228 / study

0 stars 0 forks source link

108. Convert Sorted Array to Binary Search Tree #16

Open fockspaces opened 1 year ago

fockspaces commented 1 year ago

Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.

Example 1: image

Input: nums = [-10,-3,0,5,9] Output: [0,-3,9,-10,null,5] Explanation: [0,-10,5,null,-3,null,9] is also accepted:

fockspaces commented 1 year ago

Binary Search 建 Tree,這邊只需要對 sorted Array 取中點作為 root,不斷recursion建tree即可

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        return buildTree(nums, 0, nums.size() - 1);
    }

    TreeNode* buildTree(vector<int>& nums, int l, int r) {
        if(l > r) return NULL;
        int mid = (l + r) / 2;
        TreeNode* root = new TreeNode(nums[mid]);
        root->left = buildTree(nums, l, mid - 1);
        root->right = buildTree(nums, mid + 1, r);
        return root;
    }
};