Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Subscribe to see which companies asked this question
要点就是找到中心点,然后分别递归构造左边的数和右边的数
TreeNode* sortedArrayToBST(vector<int>& nums, int beg, int end) { if (beg > end) return nullptr; int mid = (beg + end) >> 1; TreeNode* root = new TreeNode(nums[mid]); root->left = sortedArrayToBST(nums, beg, mid - 1); root->right = sortedArrayToBST(nums, mid + 1, end); return root; } TreeNode* sortedArrayToBST(vector<int>& nums) { return sortedArrayToBST(nums, 0, nums.size()-1); }
链表为了代码的简洁,我使用了二级指针,不过可读性变差了
TreeNode* sortedListToBST(ListNode* head) { if (head == nullptr) return nullptr; ListNode* fast = head; ListNode** slow = &head; while (fast->next != nullptr && fast->next->next != nullptr) { fast = fast->next->next; slow = &((*slow)->next); } TreeNode* root = new TreeNode((*slow)->val); root->right = sortedListToBST((*slow)->next); *slow = nullptr; root->left = sortedListToBST(head); return root; }