Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
cpp:
class Solution { public: TreeNode* sortedArrayToBST(vector<int>& nums) { if (nums.empty()) return nullptr; int l = 0; int r = nums.size() - 1; if (l == r) return new TreeNode(nums[l]); int m = (r >> 1); TreeNode *root = new TreeNode(nums[m]); helper(l, m - 1, root, nums, 0); helper(m + 1, r, root, nums, 1); return root; } void helper(int l, int r, TreeNode* root, vector<int>& nums, int LeftorRight) { if (l > r) return; if (l == r) { if (LeftorRight == 0) { root->left = new TreeNode(nums[l]); } else { root->right = new TreeNode(nums[l]); } return; } TreeNode *curNode; int m = l + ((r - l) >> 1); if (LeftorRight == 0) { root->left = new TreeNode(nums[m]); curNode = root->left; } else { root->right = new TreeNode(nums[m]); curNode = root->right; } helper(l, m - 1, curNode, nums, 0); helper(m + 1, r, curNode, nums, 1); } };
java:
public class Solution { public TreeNode sortedArrayToBST(int[] nums) { int len = nums.length; if (len == 0) return null; int l = 0; int r = len - 1; int m = l + ((r - l) >> 1); if (l == r) return new TreeNode(nums[l]); TreeNode root = new TreeNode(nums[m]); helper(l, m - 1, root, nums, 0); helper(m + 1, r, root, nums, 1); return root; } public void helper(int l, int r, TreeNode root, int[] nums, int LeftorRight) { if (l > r) return; if (l == r) { if (LeftorRight == 0) root.left = new TreeNode(nums[l]); else root.right = new TreeNode(nums[l]); return; } int m = l + ((r - l) >> 1); TreeNode curNode = new TreeNode(nums[m]); if (LeftorRight == 0) root.left = curNode; else root.right = curNode; helper(l, m - 1, curNode, nums, 0); helper(m + 1, r, curNode, nums, 1); } }