Try   HackMD

108. Convert Sorted Array to Binary Search Tree

Hint - DFS
/** * Definition for a binary tree node. * struct TreeNode { * int val; // Value of the node * TreeNode *left; // Pointer to the left child * TreeNode *right; // Pointer to the right child * TreeNode() : val(0), left(nullptr), right(nullptr) {} // Default constructor * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} // Constructor with value * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} // Constructor with value and children * }; */ class Solution { public: TreeNode* sortedArrayToBST(vector<int>& nums) { // Start the recursion with the full range of the array } // Helper function to recursively build the BST TreeNode* dfs(vector<int>& nums, int left, int right) { // Base case: if the current range is invalid, return nullptr // Find the middle index of the current range // Create a new node with the value at the middle index // Recursively build the left subtree with the left half of the range // Recursively build the right subtree with the right half of the range // Return the root of the constructed BST } };
Solution - DFS
/** * 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 dfs(nums, 0, nums.size() - 1); } TreeNode* dfs(vector<int>& nums, int left, int right) { if (left > right) return nullptr; int mid = (left + right) / 2; TreeNode* root = new TreeNode(nums[mid]); root->left = dfs(nums, left, mid - 1); root->right = dfs(nums, mid + 1, right); return root; } };
  • 時間複雜度:
    O(n)
  • 空間複雜度:
    O(logn)